조건에 따라 변수의 타입을 좁히거나 명확히 하는 기능
function numOrStr(a: number | string) {
if (typeof a === 'string') {
a.split(',');
} else {
a.toFixed(1);
}
}
→ typeof + if else문 / switch문 / 삼항연산자
배열 여부 체킹
function numOrNumArr(a: number | number[]) {
if (Array.isArray(a)) {
a.slice(1);
} else {
a.toFixed(1);
}
}
특정 클래스의 인스턴스인지 여부 체킹
class Animal {
feed() {}
}
class Plant {
giveWater() {}
}
function develop(param: Animal | Plant) {
if (param instanceof Animal) {
param.feed();
} else {
param.giveWater();
}
}
develop(new Animal());
클래스가 타입으로 사용될 때, 클래스 이름은 인스턴스의 타입이다
인터페이스에 식별할 수 있는 타입 속성을 기재한다
interface Person {
type: 'person';
name: string;
age: number;
}
interface Product {
type: 'product';
name: string;
price: number;
}
function print(value: Person | Product) {
if (value.type === 'person') {
console.log(value.age);
} else {
console.log(value.price);
}
}
type Lion = {
gender: 'F' | 'M', bite: boolean
};
type Ant = {
gender: 'F' | 'M', acid: boolean
};
function typeCheck(a: Lion | Ant) {
if ('bite' in a) {
a.bite = true;
} else {
a.acid = true;
}
}
JavaScript 에서 typeof null == 'object'는 true다. 따라서 object 여부 체킹 시, 먼저 null 여부를 체킹해야 한다.
function sample(data: number[] | null) {
if (data && typeof data === 'object') {
for (const number of data) {
console.log(number);
}
}
}
복잡한 타입은 is 키워드를 통해 타입 가드 전용 함수를 만들 수 있다.
타입을 판단하는 방법을 개발자가 정의하거나, 타입을 판단하는 로직을 재사용하고 싶을 때 사용된다.
프로미스 타입 가드
const isRejected = (input: PromiseSettledResult<unknown>): input is PromiseRejectedResult => {
input.status === 'rejected';
}
const isFulfilled = <T>(input: PromiseSettledResult<T>): input is PromiseFulfilledResult<T> => {
input.status === 'fulfilled';
}
const promises =
await Promise.allSettled([Promise.resolve('a'), Promise.resolve('b')]);
const errors = promises.filter(isRejected);