문제상황:
노마드 코더 React JS 마스터클래스의 #3.1 DefinitelyTyped에서 typescript를 사용하기 위해 다음과 같은 과정을 거쳤다.
1. typescript 를 설치하기위해 콘솔에 다음 커맨드 입력 -->
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
2. App.js,index.js의 확장자를 .tsx로 변경(React typescript를 사용할 경우의 확장자)
3. 기존의 'styled-components'는 typescript가 아닌 javascript로 쓰여있으므로 다음 커맨드 입력-->
npm i --save-dev @types/styled-components
(@types는 깃헙의 리포지터리로 typescript에게 styled-components가 뭔지를 설명해주는 코드로 구성)
1,2,3 단계를 거친 후에 Box 컴포넌트의 props인 bgColor를 식별하지 못하는 문제 발생
해결방법:
const Box=styled.div<{bgColor : string}>`//prop bgColor의 자료형을 string으로 지정
background-color: ${(props)=>props.bgColor};
//이하 기존코드 생략
`;
c의 자료형을 따로 string이라고 지정해주었다.
원인분석:
styled-components의 공식문서를 보면 TypeScript버전 2.9이상에서는 임의로 지정한 custom props를 사용할 경우에는 사진과 같이 태그이름 옆에 <Props이름>을 써주어야 한다고 한다.
참고링크:
Using styled components with Typescript, prop does not exist?
Here is my styled component. import * as React from 'react'; import styled from 'styled-components'; import { ComponentChildren } from 'app-types'; interface Props { children: ComponentChild...
stackoverflow.com
https://styled-components.com/docs/api#styling-components
styled-components: API Reference
API Reference of styled-components
styled-components.com