대수 타입이란 여러개의 타입을 합성해서 만드는 타입을 말한다.
let a: string | number | boolean;
a = 1;
a = "hello";
a = true;
let arr: (number | string | boolean)[] = [1, "hello", true];
type Dog = {
name: string;
color: string;
};
type Person = {
name: string;
language: string;
};
type Union1 = Dog | Person;
let union1: Union1 = { // ✅
name: "",
color: "",
};
let union2: Union1 = { // ✅
name: "",
language: "",
};
let union3: Union1 = { // ✅
name: "",
color: "",
language: "",
};
let variable: number & string; // never 타입으로 추론된다
number
타입과 string
타입은 서로 교집합을 공유하지 않는 서로소 집합이다.
따라서 변수 variable
의 타입은 결국 never
타입으로 추론된다.
대다수의 기본 타입들 간에는 서로 공유하는 교집합이 없기 때문에 이런 인터섹션 타입은 보통 객체 타입들에 자주 사용된다.
type Dog = {
name: string;
color: string;
};
type Person = {
name: string;
language: string;
};
type Intersection = Dog & Person;
let intersection: Intersection = {
name: "",
color: "",
language: "",
};