null, undefined, NaN, false 등1 && null && 3 // null 반환
undefined && '안녕' && 100 // undefined 반환
function printAll(strs: string | undefined) {
if (strs && typeof strs === "string") {
console.log(strs);
}
}
// 또는 더 간단하게
if (변수 != null) {
// null과 undefined 모두 걸러냄
}
서로 다른 속성을 가진 객체들을 구분할 때 사용
type Fish = { swim: string };
type Bird = { fly: string };
function 함수(animal: Fish | Bird) {
if ("swim" in animal) {
return animal.swim; // Fish 타입으로 narrowing
}
return animal.fly; // Bird 타입으로 narrowing
}
핵심: 배타적인 속성(서로 겹치지 않는 속성)이 있어야 narrowing 가능
클래스로 생성된 객체들을 구분할 때 사용
let 날짜 = new Date();
if (날짜 instanceof Date) {
console.log('Date 객체입니다');
}
가장 실용적인 방법으로, 각 타입에 고유한 literal 값을 부여
type Car = {
wheel: '4개',
color: string
}
type Bike = {
wheel: '2개',
color: string
}
function 함수(x: Car | Bike) {
if (x.wheel === '4개') {
console.log('차량: ' + x.color);
} else {
console.log('바이크: ' + x.color);
}
}
장점: 비슷한 구조의 객체들도 쉽게 구분 가능
개수가 정해지지 않은 파라미터를 받을 때 사용
function 전부더하기(...a: number[]) {
console.log(a); // 배열로 받아짐
}
전부더하기(1, 2, 3, 4, 5); // [1, 2, 3, 4, 5]
주의사항:
// Spread: 배열/객체 펼치기
let arr = [3, 4, 5];
let arr2 = [1, 2, ...arr]; // [1, 2, 3, 4, 5]
// Rest: 파라미터 여러 개 받기
function func(...params) { }
let { student, age } = { student: true, age: 20 };
let [a, b] = ['안녕', 100];
// 객체 파라미터
type UserType = {
user: string,
comment: number[],
admin: boolean
}
function 함수({user, comment, admin}: UserType): void {
console.log(user, comment, admin);
}
// 배열 파라미터
type 어레이 = (number | string | boolean)[];
function 함수2([a, b, c]: 어레이) {
console.log(a, b, c);
}
함수에 never 타입을 사용하려면:
1. 절대 return하지 않음
2. 함수 실행이 끝나지 않음 (endpoint가 없음)
function 함수(): never {
while (true) {
console.log(123);
}
}
function 함수(): never {
throw new Error('에러메세지');
}
function 함수(parameter: string) {
if (typeof parameter === "string") {
parameter + 1;
} else {
parameter; // never 타입이 됨 (있을 수 없는 경우)
}
}
// 함수 선언문 → void 타입
function 함수1() {
throw new Error();
}
// 함수 표현식 → never 타입
let 함수2 = function() {
throw new Error();
}
let arr = []; // strict 모드에서 never[] 타입
Never 타입은 직접 사용할 일이 거의 없음. 주로 코드 오류 감지용으로 자동 등장하므로, never가 보이면 코드를 점검해봅시다.