본문 바로가기

React/MyDiary

[Mydiary] emotion props type error

문제 발견

page 컴포넌트에서 스타일 컴포넌트로 props를 전달하려고 했지만 오류가 발생했다.

오류 코드는

Type '{ weather: string; onClick: () => void; }' is not assignable to type 'IntrinsicAttributes & IconBaseProps & { theme?: Theme | undefined; } & { children?: ReactNode; }'.
  Property 'weather' does not exist on type 'IntrinsicAttributes & IconBaseProps & { theme?: Theme | undefined; } & { children?: ReactNode; }'

 

Page 컴포넌트 :

const [weather, setWeather] = useState('');

<Sun weather={weather} onClick={() => weatherClickHandler("sun")} />

 

스타일 컴포넌트 :

export const Sun = styled(BiSun)`
  color: #ff0000;
  border: ${(props) =>
    props.weather === "sun" ? "1px solid black" : "none"};
  border-radius: ${(props) => (props.weather === "sun" ? "50%" : "none")};
`;

 

문제 분석 및 원인

page컴포넌트는 문제가 없다. 문제의 원인은 스타일 컴포넌트에서 전달받은 props의 타입을 입력하지 않았기 때문이다.

JavaScript에서는 문제없이 동작할 코드이지만 TypeScript에서는 props는 꼭 타입을 입력해주어야 하기 때문에 오류를 출력한다.

문제 해결

type weather = {
  weather: string;
};

export const Sun = styled(BiSun)<weather>`
  color: #ff0000;
  border: ${(props) =>
    props.weather === "sun" ? "1px solid black" : "none"};
  border-radius: ${(props) => (props.weather === "sun" ? "50%" : "none")};
`;

 

문제 발견 문단에서 스타일 컴포넌트의 코드와 현재 스타일 컴포넌트에 차이는 type weather = { weather: string };을 선언 해준뒤 props를 전달받는 컴포넌트에 타입을 붙여준다.

 

const 이름 = styled(컴포넌트 및 태그)<타입객체>`


`;