Typescript의 연산자
typescript에서 연산자를 이용한 타입 정의는 크게 union type과 intersection type으로 나눌 수 있습니다.
오늘은 union type과 intersection type을 사용했을 때 각각 어떻게 type이 정의 되는지 알아보도록 하겠습니다.
Union Type이란?
union type은 | 를 사용하며 type이 A이거나 B라는 의미를 가집니다.
function execute(text: string): void {
console.log(text);
}
function execute(text: number): void {
console.log(text);
}
union type을 사용하면 함수들을 합쳐 여러 개의 타입을 연결 할 수 있습니다.
function execute(text: string | number): void {
console.log(text);
}
execute("asd");
execute(123);
Union Type 사용 시 주의점
name, skill을 속성으로 가지는 Developer 인터페이스와 name, age속성으로 가지는 Person 인터페이스를 선언하고
union type으로 가지도록 함수의 parameter의 type을 지정해보겠습니다.
interface Developer{
name:string;
skill:string;
}
interface Person{
name:string;
age:number;
}
function hello(someone:Developer | Person){
someone.name; // work
someone.skill; // error
someone.age; // error
}
위의 코드를 봅시다. ask 내에서 skill과 age에 접근 시 에러가 발생하는 것을 볼 수 있습니다.
이는 type error를 막기 위해 만들어진 typescript가 확실히 존재하는 속성에만 접근이 가능하기 때문인데요,
따라서 union type 사용 시 두 인터페이스의 공통 속성에만 접근이 가능해집니다.
Intersection Type - &
union type과 다르게 intersection type은 & 을 사용하며 type이 A이면서 B라는 의미를 가집니다.
따라서 intersection type을 사용할 때에는 모든 타입에 충족해야 합니다.
interface Developer{
name:string;
skill:string;
}
interface Person{
name:string;
age:number;
}
function hello(someone:Developer & Person){
// do something
}
hello({ name: "종진", skill: "frontend", age: 19 }); // work
hello({ name: "종진", skill: "frontend"}); // error
hello({ name: "종진"}); // error