[TypeScript]styled-component 사용 시 오류(해결)

반응형

프로젝트 중 Reset css를 설정 중이였고, 'styled-components'의 'createGlobalStyle' 설정에 'DefaultTheme'을 추가 하는 과정에 생긴 오류를 정리.


코드 및 오류

코드

import { createGlobalStyle } from "styled-components";

export const GlogalStyle = createGlobalStyle`

    ...
    
    body {
        font-family: 'Gothic A1', sans-serif;
        background-color: ${(props) => props.theme.bgColor};
    }
    a {
        text-decoration: none;
    }

`

에러 문구

ERROR in src/styles/Reset.ts:68:52
TS2339: Property 'bgColor' does not exist on type 'DefaultTheme'.
    66 |     body {
    67 |         font-family: 'Gothic A1', sans-serif;
  > 68 |         background-color: ${(props) => props.theme.bgColor};
       |                                                    ^^^^^^^
    69 |     }
    70 |     a {
    71 |         text-decoration: none;

해결방법

모듈의 대한 interface를 설정

// styled-components안에 들어있는 DefaultTheme 형식 지정해주기
declare module 'styled-components' {
    export interface DefaultTheme {
        bgColor: string,
        textColor: string,
        accentColor: string,
    }
}

배운 점

TypeScript에서 기본적인 interface설정이나 이런 모듈 까지 따로 설정을 해야 하는지 몰랐다.

하나 배웠다.

반응형