.
본문 바로가기
리액트

styled-components theme 타입 지정하기

by 와칸다개발자 2022. 4. 12.

styled-components 에서 global한 속성이나 테마를 지정해주고 싶을 때 ThemeProvider를 이용한다.

 

theme 속성을 가져올 때 타입은 any타입으로 어떠한 타입이든 올 수 있다.

 

그래서 다음과 같이 작성할 때 theme의 속성이 나오지 않고 자동완성이 되지 않는다.

 

const Style = styled.div`
  background-color: ${({ theme }) => theme.backgroundColor};
`;

 

theme.ts

const theme = {
  backgroundColor: '#332abd'
}

export { theme }

 

app.tsx

<ThemeProvider theme={theme}>
	{children}
</ThemeProvider>

 

물론 속성이름만 맞는다면 아무 문제없지만 그렇지 않을 때 예기치 못한 오류를 발생시킬 수 있다.

 

theme 의 타입을 지정해보자.

 

공식 doc는 여기다.

 

https://styled-components.com/docs/api#create-a-declarations-file

 

styled-components: API Reference

API Reference of styled-components

styled-components.com

 

먼저 styled.d.ts 파일을 작성해준다.

 

d.ts 파일은 타입스크립트에서 사용하도록 별도로 타입 정보를 설정하는 파일이다.

 

styled.d.ts 

import 'styled-components';

declare module 'styled-components' {
  export interface DefaultTheme {
    backgroundColor:string;
  }
}

declare module로 선언시 절대 경로로 styled-components 모듈에서 작성한 별도의 타입을 가져올 수 있다.

 

theme.ts

import { DefaultTheme } from 'styled-components';

const theme: DefaultTheme = {
  backgroundColor: '#332abd'
}

export { theme }

ThemeProvider에 들어갈 theme 파일을 작성해 주었다. 이제 끝이다.

 

위 사진과 같이 타입이 지정되어 자동완성이 되는것을 볼 수 있다.

댓글