본문 바로가기

JS&TS Essential/Type

Type의 확장

Typescript에서 타입지정을 위해 Type alias와 Interface를 사용할 수 있는데,

이렇게 지정된 type들을 확장하는 기능도 지원하고 있다.

어떻게 확장할 수 있는지 배워보도록 하자!

 

 


Intersection

interface animal {
    readonly name: string;
    age: number;
}

type bird = animal & {
    wing: number;
}

 

type alias 기능을 사용할 때는 &를 사용해 연산하듯이 두 타입을 합칠 수 있다.

이를 `intersection`이라고 부르고, interface나 type alias로 지정된 타입을 모두 결합할 수 있다.

 

 


상속

interface animal {
    readonly name: string;
    age: number;
}

interface fish extends animal {
    fin: number;
}

 

interface 기능을 사용할 때는 `extends`라는 키워드를 통해서 타입을 확장할 수 있다.

이를 상속이라고 부르고, interface나 type alias로 지정된 type을 모두 상속받을 수 있다.

 

 


여러 타입 합성

interface papaer {
    isCover: boolean;
    width: number;
    height: number;
}

type pageInfo = {
    title?: string;
    content: string;
    pageNumber: number;
}

interface IBook extends papaer, pageInfo {
    bookName: string;
}

type TBook = papaer & pageInfo & {
    bookName: string;
}

 

extends와 intersection을 이용해 interface나 type alias로 지정된 여러 타입들을 합치는 것도 가능하다.

'JS&TS Essential > Type' 카테고리의 다른 글

객체 Type 알아보기  (0) 2021.11.15
Type 추론  (0) 2021.11.09
type alias와 interface  (0) 2021.03.04
TypeScript의 type 알아보기  (0) 2021.03.03