대수 타입(Algebraic type)

1 min read
Table of contents

대수 타입(Algebraic type)
대수 타입이란 여러개의 타입을 합성해서 만드는 타입을 말한다.
합집합(Union) 타입
let a: string | number | boolean;
a = 1;
a = "hello";
a = true;
Union 타입으로 배열 타입 정의하기
let arr: (number | string | boolean)[] = [1, "hello", true];
Union 타입과 객체 타입
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: "",
};
교집합(Intersection) 타입
let variable: number & string; // never 타입으로 추론된다
number
타입과 string
타입은 서로 교집합을 공유하지 않는 서로소 집합이다.
따라서 변수 variable
의 타입은 결국 never
타입으로 추론된다.
대다수의 기본 타입들 간에는 서로 공유하는 교집합이 없기 때문에 이런 인터섹션 타입은 보통 객체 타입들에 자주 사용된다.
Intersection 타입과 객체 타입
type Dog = {
name: string;
color: string;
};
type Person = {
name: string;
language: string;
};
type Intersection = Dog & Person;
let intersection: Intersection = {
name: "",
color: "",
language: "",
};
0
Subscribe to my newsletter
Read articles from woodstock directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

woodstock
woodstock
안녕하세요! 프론트엔드 개발자 woodstock입니다. 저는 매일 조금씩 발전하고자 하는 마음으로 개발공부를 시작했고, 이 블로그는 그 과정에서 배우고 성장하는 이야기를 담고 있습니다. 여러분의 피드백과 조언은 언제나 환영합니다! 함께 배우고 성장하는 과정을 즐길 수 있기를 기대합니다.