TypeScript : 연산자 타입 (유니언 타입, 인터섹션 타입)

Union Type

Union Type은 JavaScript에서 AND 연산자와 OR 연산자를 생각하면 이해하기 쉽습니다.

1
2
3
function logText(text: string | number) {
//...
}
1
2
3
4
5
6
7
8
9
function getBirth(birth: number | string) {
if (typeof birth === "number") {
return birth + "년";
}
if (typeof birth === "string") {
return birth;
}
return new TypeError("age muse be number of string");
}

Intersection Type

1
2
3
4
5
6
7
8
9
10
11
interface Person {
name: string;
age: number;
}

interface Developer {
name: string;
skill: number;
}

type Capt = Person & Developer;