typeScript
๋?
JS๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ํ ์ธ์ด์ด๋ฉฐ, ๊ฐํ์ ์ธ์ด๋ก ํ๋ก๊ทธ๋๋ฐ ์ธ์ด๊ฐ ์คํ๋๊ธฐ ์ ์ type์ ํ์ธํด ์ค๋ค.
npx create-react-app (ํด๋๋ช
) --template typescript
yarn create react-app (ํด๋๋ช
) --template typescript
๐๐ป ์ ํด๋๋ก ํ์ ์คํฌ๋ฆฝํธ ์ค์
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
or
yarn add typescript @types/node @types/react @types/react-dom @types/jest
๐๐ป ๊ธฐ์กด์ ํด๋์์ ํ์ ์คํฌ๋ฆฝํธ ์ถ๊ฐ
๐ซย ๋๋ถ๋ถ์ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ ์๋ฐ์คํฌ๋ฆฝํธ ๊ธฐ๋ฐ์ผ๋ก ๋ง๋ค์ด์ก๊ธฐ ๋๋ฌธ์ ํ์ ์คํฌ๋ฆฝํธ๋ ๊ทธ ๋ชจ๋๋ค์ ์ดํดํ์ง ๋ชปํ๋ค. ๋ฐ๋ผ์ ํ์ ์คํฌ๋ฆฝํธ๊ฐ ์ดํดํ ์ ์๋ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ๋ฐ๋ก ์ค์นํด ์ฃผ์ด์ผ ํ๋ค.
styled-components
npm i --save-dev @types/styled-components
yatn add --dev @types/styled-components
๐ฑ ํ์ ์คํฌ๋ฆฝํธ์์๋ ์ ๋ฌ ๋ฐ์์ผํ props๋ฅผ ์ ์ํด ์ค ์ ์๋ค. PropsTypes ์ฌ์ฉ์ ์ค๋ฅ๋ฅผ ์คํ ํ ์ฝ์์์ ํ์ธํ ์ ์์์ง๋ง, ํ์ ์คํฌ๋ฆฝํธ์์ interface๋ฅผ ํตํด props๋ฅผ ์ ์ํด ์ฃผ๋ฉด ์คํ ์ ์๋ ์ค๋ฅ๋ฅผ ๊ฐ์งํ ์ ์์๋ฟ๋ง ์๋๋ผ ์๋์์ฑ์ ํตํด ์ฝ๋์ค๋ฅ๋ฅผ ์ค์ผ ์ ์๋ค!
import styled from "styled-components";
interface CircleProps {
bgColor: string;
}
const Container = styled.div<CircleProps>`
width: 200px;
height: 200px;
background-color: ${(props) => props.bgColor};
border-radius: 100px;
`;
function Circle({ bgColor }: CircleProps) {
return <Container bgColor={bgColor} />;
}
export default Circle;
๐๐ป Circle
๊ณผ Container
๋ bgColor
๋ฅผ ๊ผญ props๋ก ์ ๋ฌ๋ฐ์์ผ ํจ์ ๋ช
์ํด์ค. ContainerProps
interface๋ฅผ ๋ฐ๋ก ์ ์ํ์ฌ ์ฌ์ฉํด๋ ๋์ง๋ง, CircleProps์ ๋ด์ฉ์ด ๊ฒน์น๋ฏ๋ก ๊ทธ๋๋ก ์ฌ์ฉํด์ฃผ์ด๋ ๋จ.
๐ป useState hook์ ์ฌ์ฉํ ๋ ํ์ ์ง์ ํด์ฃผ๊ธฐ
const [value, setValue] = useState<string>("");
์ฌ๋ฌ ๊ฐ์ง์ ํ์
์ ๊ฐ์ผ๋ก ๋ฐ๊ณ ์ถ๋ค๋ฉด <string | number>
์ ํ์์ผ๋ก ์ ์ด์ฃผ๋ฉด ๋๋ค.