TypeScript

์œค์„œยท2023๋…„ 9์›” 28์ผ
0

[Nomad Coders] React JS Master Class

๋ชฉ๋ก ๋ณด๊ธฐ
2/5

๐Ÿ“š TypeScript

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

Typing the Props

๐ŸŒฑ ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ์—์„œ๋Š” ์ „๋‹ฌ ๋ฐ›์•„์•ผํ•  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์™€ ๋‚ด์šฉ์ด ๊ฒน์น˜๋ฏ€๋กœ ๊ทธ๋Œ€๋กœ ์‚ฌ์šฉํ•ด์ฃผ์–ด๋„ ๋จ.

State

๐Ÿ‘ป useState hook์„ ์‚ฌ์šฉํ•  ๋•Œ ํƒ€์ž… ์ง€์ •ํ•ด์ฃผ๊ธฐ

const [value, setValue] = useState<string>("");

์—ฌ๋Ÿฌ ๊ฐ€์ง€์˜ ํƒ€์ž…์„ ๊ฐ’์œผ๋กœ ๋ฐ›๊ณ  ์‹ถ๋‹ค๋ฉด <string | number>์˜ ํ˜•์‹์œผ๋กœ ์ ์–ด์ฃผ๋ฉด ๋œ๋‹ค.

Nomad Coders React JS ๋งˆ์Šคํ„ฐ ํด๋ž˜์Šค #3

profile
๋‚˜์˜ ์กฐ๊ฐ๋ฐฐ

0๊ฐœ์˜ ๋Œ“๊ธ€