일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
- RGB
- 일반 형제 결합자
- iframe
- 임베디드
- padding 속성
- Live Server
- iframe 태그
- Checked 의사 클래스
- reveal in file explorer
- html tag i
- sub태그
- html
- 자식결합자
- css
- not 의사클래스
- height속성
- RGBA
- sup태그
- background-color 속성
- 전체 선택자
- id 선택자
- go live
- width속성
- tag html
- html 태그
- i 태그
- 아두이노
- br 태그
- focus 의사클래스
- 인접 형제 결합자
- Today
- Total
so woon!
[TYPESCRIPT] state, generic 본문
학습일 : 2023. 03. 31
<Circle.tsx>
이러한 코드가 있다고 치자
useState를 이용하여 초깃값을 1로 줘놓은 상태이다.
function Circle({ bgColor, borderColor, text = "default text" }: CircleProps) {
const[counter, setCounter] = useState(1);
return (
<Container bgColor={bgColor} borderColor={borderColor ?? bgColor}>
{text}
</Container>
);
}
export default Circle;
setCounter를 hover 해보면
const setCounter: React.Dispatch<React.SetStateAction<number>>
이 뜨는데
number를 이용하는 액션이란 것을 알 수 있다.
이것은 Typescript가 초깃값 useState(1); 을 가지고 추론한 것이다.
즉, useState(여기)
여기라고 적힌 곳에 number 타입이 들어가면
setCounter도 number 타입이 될 것이라는 것을 타입스크립트가 알아채는 것이다.
string, boolean 등등 마찬가지이다.
<Circle.tsx>
이번엔 다르게 useState(true); 로 작성해준다면
setCounter(false); 도 역시 boolean 이므로
에러가 나지 않는다.
useState(true)를 초깃값으로 줬는데
setCounter에서 number로 준다면
아래처럼 빨간줄이 그어지고 에러를 발생시킨다.
number로 주고 number로 적어주면
아무 일이 발생되지 않는다.
number로 초깃값을 줬는데
setCounter로 string을 적어주었기 때문에
아래처럼 에러가 생긴다!
초깃값으로 똑똑하게 알아차리는 타입스크립트 칭찬해
여기서 만약
초깃값에 상관 없이
string이나 boolean 타입이 될 수도 있게끔 설정하고 싶다면?
제네릭으로 작성해주면 된다
useState<string|boolean>(true) 를 작성해줌으로 인해
초깃값 boolean 에 상관 없이 string이나 boolean 타입이 될 수 있다.
function Circle({ bgColor, borderColor, text = "default text" }: CircleProps) {
const[value, setValue] = useState<string|boolean>(true);
setValue(false);
setValue(3);
setValue("ddd");
return (
<Container bgColor={bgColor} borderColor={borderColor ?? bgColor}>
{text}
</Container>
);
}
export default Circle;
제네릭으로 string 또는 boolean을 적어주었기 때문에
number 타입을 적어준
setValue(3) 은 에러가 발생함을 볼 수 있다.
에러를 잡고싶으면
useState<string|boolean|number>(true);
이렇게 number도 추가해주면 된다.
'Typescript > 개념정리' 카테고리의 다른 글
[TYPESCRIPT] typescript & styled-components 테마 연결 (0) | 2023.04.01 |
---|---|
[TYPESCRIPT] form 구현, form에 타입 적용하기 (0) | 2023.04.01 |
[TYPESCRIPT] optional props (0) | 2023.03.31 |
[TYPESCRIPT] interface 사용하기 (0) | 2023.03.30 |
[TYPESCRIPT] typescript project의 시작 (0) | 2023.03.30 |