My Boundary As Much As I Experienced

d.ts파일 설정 본문

FrontEnd/TypeScript

d.ts파일 설정

Bumang 2024. 2. 14. 14:30

emotion으로 ThemeProvider 세팅을 하던 도중,

theme의 타입이 불명확해서, 아래 경우에 color에 타입을 찾을 수 없다는 둥 에러가 났다.

background-color: ${({ theme }) => theme.color.gray100};

 

 

처음엔 typescript의 interface를 사용해서 타입지정을 다 해주려 했다.

interface Theme {
color: {
darkGray900: string;
darkGray800: string;
darkGray700: string;
darkGray600: string;
darkGray500: string;
darkGray400: string;
...

 

그런데 interface로 만든 Theme type을 실제 theme객체에 위 타입을 적용해도 맨 위 에러는 사라지지 않았다.

(추가로 내가 이전에 styled-component에서 사용하던 `CSSProp`이 emotion에는 없는 케이스도 있는 등 emotion의 타입지정은 또 styled-components와 다른 부분이 있어 애먹었다.)

 

 

결국 구글링 결과, d.ts파일을 만들어서 타입을 제공해주는 방법을 찾았다.

지금까지 d.ts 파일을 조금 수정해보는 정도는 했지만 내가 직접 만들어본 적은 없었는데

직접 해보니 타입 핸들링하기에 매우 좋은 테크닉인거 같다.

 

import '@emotion/react';
import { Interpolation } from '@emotion/react';

type themeId = 'color' | 'font';

declare module '@emotion/react' {
  export interface Theme {
    color: {
      gray900: string;
      gray800: string;
      gray700: string;
      gray600: string;
      gray500: string;
      gray400: string;
      gray300: string;
      gray200: string;
      gray100: string;
      error: string;
      success: string;
    };
    font: {
      subtitle1: Interpolation<object>;
      subtitle2: Interpolation<object>;
      subtitle3: Interpolation<object>;
      subtitle4: Interpolation<object>;
      subtitle5b: Interpolation<object>;
      subtitle5r: Interpolation<object>;

      body1b: Interpolation<object>;
      body1r: Interpolation<object>;
      body2b: Interpolation<object>;
      body2r: Interpolation<object>;
      body3b: Interpolation<object>;
      body3r: Interpolation<object>;

      caption1b: Interpolation<object>;
      caption1l: Interpolation<object>;
      caption2b: Interpolation<object>;
      caption2r: Interpolation<object>;
    };
  }
}

 

 

`declare module <moduleName>`을 하면 특정 모듈에 타입을 지정할 수 있다.

export 다음에 interface 혹은 type을 이용하여 브라켓 안에 타입들을 제공해주면 된다.

 

`declare namespace <nameYouWant>` 로 하면 이 프로젝트 전역으로 사용할 타입을 제공해줄 수 있다.

또한 export 다음에 타입들을 써주면 된다.

 

 

참고자료:

https://velog.io/@yeogenius/React-Emotion.js-%EB%A1%9C-Theme-%EC%84%A4%EC%A0%95%ED%95%98%EA%B8%B0

 

velog

 

velog.io

 

 

-----

+ 추가 에러:

해결 안 됐다. IDE에선 타입에러가 사라졌는데 실제 로컬 서버 돌려보면 아직도 타입을 못찾는다고 한다..ㅠㅠ