Search
📜

유니온 타입 & 교차 타입

타입을 속성의 집합이 아닌 값의 집합이라고 생각해야 합집합, 교집합 이해가 가능
type A = never & string; type B = never | string; type C = unknown & string; type D = unknown | string;
TypeScript
복사
정답
대수 타입
유니온 타입(|)
2개 이상의 타입을 조합 (합집합)
단, 유니온 타입으로 선언한 값은 포함된 모든 타입이 공통으로 가진 속성에만 접근 가능
interface CookingStep { orderId: string; price: number; } interface DeliveryStep { orderId: string; time: number; distance: string; } function getDeliveryDistance(step: CookingStep | DeliveryStep) { return step.distance; // 🚨 Property ‘distance’ does not exist on type ‘CookingStep | DeliveryStep’ // 🚨 Property ‘distance’ does not exist on type ‘CookingStep’ }
TypeScript
복사
각 타입의 예시
인터섹션 타입 (&)
2개 이상의 타입을 합쳐 필요한 모든 속성을 가진 타입 생성 (교집합)
각 타입의 모든 속성을 가진 단일 타입이 생성 됨
값의 집합이기 때문에 공통 속성이 없어도 never가 아닌 모든 속성을 포함한 집합이 됨
각 타입의 예시
타입이 호환되지 않는 경우의 예시
유니온 타입과 인터섹션 타입의 사례별 비교
유니온
type Person = { name: string; } type Student = { school: string; } type Union = Person | Student const union: Union = { name: 'k', school: 'j', } const person: Union = { name: 'k', } const student: Union = { school: 'j', } // Type '{}' is not assignable to type 'Union'.(2322) const nothing: Union = {} // Object literal may only specify known properties, // and 'more' does not exist in type 'Union'.(2353) const more: Union = { name: 'k', school: 'j', more: 'a' } console.log(union) // type은 Union으로 추론 됨 console.log(person) // type은 Person으로 추론 됨 console.log(student) // type은 Student로 추론 됨 // Property 'name' does not exist on type 'Union'. // Property 'name' does not exist on type 'Student'.(2339) console.log(union.name) if('name' in union) console.log(union.name)
TypeScript
복사
인터섹션
type Person = { name: string; } type Student = { school: string; } type Intersection = Person & Student const intersection: Intersection = { name: 'k', school: 'j', } // Type '{ name: string; }' is not assignable to type 'Intersection'. // Property 'school' is missing in type '{ name: string; }' // but required in type 'Student'.(2322) const person: Intersection = { name: 'k', } // Type '{ school: string; }' is not assignable to type 'Intersection'. // Property 'name' is missing in type '{ school: string; }' // but required in type 'Person'.(2322) const student: Intersection = { school: 'j', } // Type '{}' is not assignable to type 'Intersection'. // Property 'name' is missing in type '{}' // but required in type 'Person'.(2322) const nothing: Intersection = {} // Object literal may only specify known properties, // and 'more' does not exist in type 'Intersection'.(2353) const more: Intersection = { name: 'k', school: 'j', more: 'a' } console.log(intersection) // type은 Intersection console.log(person) // type은 Intersection console.log(student) // type은 Intersection // Property 'name' does not exist on type 'Intersection'. // Property 'name' does not exist on type 'Student'.(2339) console.log(intersection.name) if('name' in intersection) console.log(intersection.name)
TypeScript
복사