→ 거의 같지만 다른 단어이다.
→ 프로그래밍 언어가 작동하기 전에 type을 확인해준다.
const plus = (a:number,b:number) => a+b
→ 알아서 tsconfig.json
파일을 만들어준다.
$ npx create-react-app my-app --template typescript
$ yarn create react-app my-app --template typescript
$ npm install --save typescript @types/node @types/react @types/react-dom @types/jest
npm i --save-dev @types/styled-components
@types ⇒ type definition : 스타일드 컴포넌트의 소스코드를 보고 Typescript로 보내주고 싶은 내용을 보내준다. → 이 라이브러리가 뭔지 알려주는 역할= TS에서 prop 을 받아오는 방법
= object 설명해주는 것
<div>
<Circle bgColor="teal"/>
<Circle bgColor="tomato"/>
</div>
interface CircleProps {
bgColor:string;
}
<Circle bgColorX="tomato"/>
⇒ 오류가 표시된다.const Circle = ({bgColor}:CircleProps)=>{
return (<Container bgColor ={bgColor}/>)}
const Circle = (props:CircleProps) =>{
return (<container bgColor ={props.bgColor} />)}
{bgColor}:CircleProps)
= bgColor
의 타입은 CircleProps
의 object이다
props:CircleProps
라고 사용하는게 더 편리하다.interface ContainerProps{
bgColor:string;
}
const Container = styled.div<ContainerProps>`
width : 200px;
height : 200px;
background-color : ${props=>props.bgColor};
border-radius: 100px ;
`;
${props=>props.bgColor}
interface CircleProps {
bgColor:string;
borderColor? : string
}
borderColor? : string
⇒ optional 하게 값을 가진다.
const Circle = (props:CircleProps)=>{
return (
<Container bgColor = {props.bgColor} borderColor={props.borderColor??"pink"} />
)}
borderColor={props.borderColor??"pink"}
⇒ 선택적으로 값을 받아오기 때문에 값이 없으면 undefined가 들어오게 된다
결국 값이 없으면 기본값을 만들어 주면 된다.
컨테이너에서 받기
interface ContainerProps{
bgColor:string;
borderColor? :string;
}
borderColor? :string;
== borderColor:string | undefined;
이렇게 적어도 무방하다
const Circle = ({bgcolor,borderColor,text="defualt")=>{}
const [counter,setCounter] = useState(1)
state 값을 하나 만들어 준다 →
초기값이 1이 들어가있으면 counter의 타입은 자동으로 number라고 예측된다.
useState<number>(0)
, useState<string>('1')
, useState<number|string>(0)
const onChange =(event:React.FormEvent<HTMLInputElement>)=>{
// setValue(e.currentTarget.value)
const {
currentTarget:{value}
} = event
setValue(value)
}
event:React.FormEvent<HTMLInputElement>
const onSubmit =(event:React.FormEvent<HTMLFormElement>)=>{
event.preventDefault();
console.log("hello",value)
}