Typescript와 함께 동적 CSS 스타일 사용하기

import styled from "@emotion/styled"; const StyledPropsTest = styled.div` width: 120px; height: 40px; font-size: 25px; background: ${(props) => (props.testProps ? "blue" : "red")}; color: white; `; const StyledTest = ({testprops}) => { return( <StyledPropsTest testProps={testprops}>Prop Test</StyledPropsTest> ) } export default StyledTest;
컴포넌트 내부에서 사용하는 변수를 CSS에 전달하여 동적 스타일을 적용하기 위해서는 위와 같이 props를 전달하는 방법이 있습니다.
하지만 Typescipt를 사용하여 custom props를 사용하면 다음과 같은 에러를 만나게 됩니다.

(property) testProps: boolean
Type ‘{ children: string; testProps: boolean; }’ is not assignable to type ‘IntrinsicAttributes & { theme?: Theme | undefined; as?: ElementType<any> | undefined; } & ClassAttributes<HTMLDivElement> & HTMLAttributes<…>’.
Property ‘testProps’ does not exist on type ‘IntrinsicAttributes & { theme?: Theme | undefined; as?: ElementType<any> | undefined; } & ClassAttributes<HTMLDivElement> & HTMLAttributes<…>’.ts(2322)
이는 타입스크립트에서 props의 타입을 체크하기 때문인데요.
다음과 같이 간단하게 <{data:type}>의 타입 단언(Type Assertion)으로 해결할 수 있습니다.
const StyledPropsTest = styled.div<{testProps:boolean}>` width: 120px; height: 40px; font-size: 25px; background: ${(props) => (props.testProps ? "blue" : "red")}; color: white; `;
다음과 같이 에러가 사라진 것을 확인할 수 있습니다.

