티스토리 뷰
타입 확정하기 Narrowing & Assertion
: 타입이 아직 하나로 확정되지 않았을 때 Type Narrowing을 사용
1. Narrowing 판정 문법
- typeof 변수
- 속성명 in 오브젝트자료
- 인스턴스 instanceof 부모
function 함수(x: number | string) {
if (typeof x === 'string') { // if문으로 Narrowing
return x + '1';
} else {
return x + 1;
}
}
2. null & undefined 타입 체크
- && 연산자
function 함수(x: string | undefined) {
if (x && typeof x === 'string') {
}
}
- in 키워드
type Fish = { swim: string };
type Bird = { fly: string };
function 동물(animal: Fish | Bird) {
// if (typeof animal === ) { // typeof 연산자는 number, stringm, boolean, object 이런식으로만 판정 가능
if ('swim' in animal) {
// in 키워드로 서로 배타적인 속성을 가진 타입을 체크 가능
animal.swim;
}
}
- instanceof 연산자
오브젝트 instanceof 부모class
3. typeof 연산자로 narrowing 못할 때
- 비슷한 object 타입일 경우: literal type을 만들어두면 narrowing이 편함
type CarType = {
wheel: '4개'; // literal type
color: string;
};
type BikeType = {
wheel: '2개'; // literal type
color: string;
};
function 탈것(x: CarType | BikeType) {
if (x.wheel === '4개') {
console.log('x는 CarType');
}
}
assertion : 타입 덮어쓰기
- 유니언 타입(타입이 둘 이상)을 하나로 확정 지을 때 사용. 타입이 하나일 땐 사용x
- 무슨 타입이 들어올지 확실히 알 때 사용 - 버그추적 힘듬
- * 타입 지정만 하지 실제로 타입을 바꿔주지는 않음
function 함수2(x: number | string) {
let array: number[] = [];
array[0] = x as number;
}
'Language > TypeScript' 카테고리의 다른 글
| [TypeScript] Literal Types (0) | 2023.07.11 |
|---|---|
| [TypeScript] type 키워드, object readonly (0) | 2023.07.11 |
| React에서 TypeScript 사용2 - redux (0) | 2023.07.03 |
| React에서 TypeScript 사용 (0) | 2023.07.03 |
| [TypeScript] 함수 타입 (0) | 2023.06.29 |
댓글
