[Typescript] 09. 타입 확장
포스트
취소

[Typescript] 09. 타입 확장

Extending Types

class가 상속이 되듯이, type도 상속이 가능하다.

1
2
3
4
5
6
7
8
9
10
11
type BasicAddress = {
  name?: string;
  street: string;
  city: string;
  country: string;
  postalCode: string;
}
 
interface AddressWithUnit extends BasicAddress {
  unit: string;
}

우편번호를 입력 받을 때, 공통적으로 입력 받아야 하는 항목에 대해서 우선적으로 정의하고 추후에 선택사항을 따로 정의한 interface에 상속하는 방법으로 type을 확장시킬 수 있다.

다만, extends 키워드는 interface에서만 사용할 수 있다.

다중 상속

1
2
3
4
5
6
7
8
9
10
11
12
13
14
interface Colorful {
  color: string;
}
 
interface Circle {
  radius: number;
}
 
interface ColorfulCircle extends Colorful, Circle {}
 
const cc: ColorfulCircle = {
  color: "red",
  radius: 42,
};

,(콤마)를 통해 상속받을 대상을 여러 개 지정할 수 있다.

교차 타입

비록 type에서 extends를 사용하진 못하지만 비슷한 효과를 낼 수 있는 방법이 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
type testA = {
    a: number,
}
type testB = {
    b: string,
}
type testC = testA & testB & { good: boolean };

const obj: testC = {
    a: 1,
    b: 'asd',
    good: true,
}

& 연산자를 사용하면 여러 type을 하나로 묶을 수 있다.

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.