Styled-Components와 TypeScript를 함께 사용할 때 아래와 같은 에러가 발생한다.
Property 'isSelected' does not exist on type
'Pick<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>,
HTMLDivElement>, "key" | keyof HTMLAttributes<HTMLDivElement>>
& { ...; } & ThemeProps<...>'
Styled-Components가 전달받은 프로퍼티에 타입이 지정되어 있지 않아 발생하는 에러이다.
크게 두 가지 해결법이 있다.
방법1
const SStyledBookmark = styled.div`
color: ${({ isSelected, theme } : { isSelected : any, theme : any}) =>
...
단순하게 프로퍼티에 타입을 명시해주면 된다. 하지만 중복되는 프로퍼티가 많다면 방법2를 사용하는 것이 좋다.
방법2
interface Props {
isSelected?: boolean;
horizontal?: string;
vertical?: string;
width?: string;
height?: string;
justify_content?: string;
align_items?: string;
flex?: string;
selected?: boolean;
forPopup?: boolean;
isOpened?: boolean;
expand?: boolean;
}
const SStyledBookmark = styled.div<Props>`
color: ${({ isSelected, theme }) =>
사용자 지정 프로퍼티들을 interface로 만들어 컴포넌트에 확장시키는 방법이다. Styled-Components에서 지원하는 최신 방법이다.
프로퍼티를 사용하고자 하는 컴포넌트에 위와 같이 확장시켜주면 된다.
'React > TypeScript' 카테고리의 다른 글
[TS] TypeScript Object 다루기 (0) | 2022.04.10 |
---|---|
[TS] React Typescript 변환하기 (0) | 2022.04.09 |