interface
s allowed us to build up new types from other types by extending them. TypeScript provides another construct called intersection types that is mainly used to combine existing object types.
인터섹션 타입은 기존 객체 타입을 결합하는데 주로 사용합니다.
type Admin = {
name: string;
privileges: string[];
};
type Employee = {
name: string;
startDate: Date;
};
위의 타입을 가지는 두 객체가 있습니다.두객체를 결합해 인터섹션 타입을 이용한다면 아래와 같습니다
type ElevatedEmpployee = Admin & Employee;
const e1: ElevatedEmpployee = {
name: "Lee",
privileges: ["create-server"],
startDate: new Date(),
};
만약 요소중 하나가 빠지게 된다면 아래와같은 에러를 만나게 되며, 오타가 발생했을 시에도 에러를 발생해 사용자가 실수하는 것을 막아줄 수 있습니다
const e1: ElevatedEmpployee = {
name: "Lee",
privileges: ["create-server"],
};
/*src/app.ts:8:3
8 startDate: Date;
~~~~~~~~~
'startDate' is declared here.*/
유니언 타입에서는, 타입간의 공통점이 있는 타입을 추출해 사용하게 됩니다
type Combinable = string | number;
type Numeric = number | boolean;
type Universal = Combinable & Numeric;//number
인터페이스와 인터섹션 둘다 두가지 타입을 결합하는데 사용외되나, 전자의 경우 extends
를 이용한다는 차이점을 보이고 있습니다. 또한 전자의 경우에는 class의 경우에는 instanceof
를 사용할 수 없습니다
타입 가드 혹은 단어 그대로 타입 보호 라고 하며, 타입 가드를 이용시 유니언을 사용할때 있어 조금 더 용이합니다.
아래의 경우에는 문자열 혹은 숫자의 타입을 가지는 타입입니다.
type Combinable = string | number;
const PLUS = (a: Combinable, b: Combinable) => {
if (typeof a === "string" || typeof b === "string") {
return a.toString() + b.toString();
}
return a + b;
};
그래서 이를 이용해 주기 위해, 각각의 인수의 타입을 확인해 둘중 하나의 타입이 문자열이라면 문자열로 형변환해서 이용하고, 그외의 경우에는 숫자를 더해주는 방향으로 진행되게되었습니다