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 파일을 작성해 주었다. 이제 끝이다.
위 사진과 같이 타입이 지정되어 자동완성이 되는것을 볼 수 있다.
'리액트' 카테고리의 다른 글
useEffect 에서 object 타입 dependency 다루기(with:useAxios) (0) | 2022.04.22 |
---|---|
Redux는 왜 쓰는 걸까?(1) (0) | 2022.02.21 |
React에서 setInterval 작성하기 (0) | 2021.11.22 |
댓글