Study/TypeScript

[TS] basic Union Type & Intersection Type

taecongs 2023. 10. 12. 12:09

 


알고있으면 좋은 Typescript Tip✨


유니온 타입(basic Union Type)이란?

  • 자바스크립트의 OR 연산자(||)와 같이 A이거나 B이다 라는 의미의 타입이다.
  • 쉽게 말해, 둘 이상의 다른 데이터 타입을 하나로 결합하는 방법을 제공하는 기능이다. 이것은 여러 타입 중 하나가 될 수 있는 변수, 매개변수 또는 속성을 정의하거나 표현할 때 유용하다.
let myVariable: number | string;
myVariable = 10;        // 유효
myVariable = "Hello";   // 유효
myVariable = true;      // 오류, boolean 타입은 유니온 타입에 포함되어 있지 않음
  • 위의 예시에서myVariable은 숫자 또는 문자열 중 하나가 될 수 있다. 만약 다른 타입을 할당하려고 하면 TypeScript 컴파일러가 에러를 발생시킨다.

 

(1)유니온 타입(basic Union Type) 정의

// string과 number, boolean 타입을 허용
var foo: string | number | boolean; 


//함수 인자에 유니온타입 선언
function unionFunction(value: string | number) {
  // string과 number 타입만 인자로 받을 수 있다.
  console.log(value);
}

unionFunction('hello!');
unionFunction(200);

// boolean 타입은 허용하지 않아서 문법 오류 발생
unionFunction(true);
  • | (파이프라인) 키워드를 이용해서 유니온 타입 지정을 한다.
  • 유니온 타입을 이용하여 확장하는 만큼 타입 허용이 된다.
  • 유니온 타입에서 허용하지 않은 타입일 경우 문법 오류가 발생한다.

 

(2)유니온 타입(basic Union Type) 특징

interface Developers {
  name: string;
  skill: string;
}
interface Persons {
  name: string;
  age: number;
}

function askSomeone(someone: Developers | Persons) {
  someone.name;
  
  // 두 개의 인터페이스 중 보장된 속성에 대해서만 인정
  someone.skill 
}
  • someone인자에 Developers와 Persons 인터페이스를 유니온으로 지정하였기 때문에 두개의 인터페이스 속성을 모두 받을 수 있으리라 생각하지만 불가능하다.
  • 두개의 타입 중 어떤 타입의 속성이 전달 될 지 알 수 없기 때문에, 두개의 타입 중 보장된 속성에 한하여 타입스크립트가 문법을 인정한다.

 

(3)유니온 타입(basic Union Type) 과 인터섹션 타입(Intersection Type) 관계

interface Developers {
  name: string;
  skill: string;
}

interface Persons {
  name: string;
  age: number;
}

// 유니온타입 지정
function askSomeone1(someone: Developers | Persons) {
  someone.name;
  someone.skill 
}

// 인터페이스 Developers의 규격대로 인자 전달 👉 문법 오류 없음
askSomeone1({ name: '요리사', skill: '양식' }); 

// 인터페이스 Persons의 규격대로 인자 전달 👉 문법 오류 없음
askSomeone1({ name: '야구선수', age: 30 }); 


// 인터섹션타입 지정
function askSomeone2(someone: Developers & Persons) {
  someone.name;
  someone.skill;
  someone.age
}

// 인터페이스 Developers의 규격대로 작성해도 문법 오류가 뜸
askSomeone2({ name: '요리사', skill: '양식' }) 

// Developers와 Persons의 공통 속성 name과 각각의 속성 skill, age를 모두 포함한 규격대로 작성해야 함
askSomeone2({ name: '야구선수', skill: '정교한 타격', age: 30 })
  • someone인자에 Developers와 Persons 인터페이스를 유니온으로 지정하였기 때문에 두개의 인터페이스 속성을 모두 받을 수 있으리라 생각하지만 불가능하다.
  • 두개의 타입 중 어떤 타입의 속성이 전달 될 지 알 수 없기 때문에, 두개의 타입 중 보장된 속성에 한하여 타입스크립트가 문법을 인정한다.