far

[Typescript] Type과 Interface의 차이점 본문

Typescript

[Typescript] Type과 Interface의 차이점

Eater 2023. 3. 12. 01:49

Type (Type Alias)

type AnimalType = {
    animal: 'Dog';
    age: number;
    name: string;
 };

Interface

interface AnimalInterface {
    animal: 'Dog';
    age: number;
    name: string;
}

 

공식문에서는 interface를 사용하다 문제가 발생했을 때 type을 사용하기를 권장하고있다. 하지만 작업을 하다보면 type에만 적용되는 기능들이 있어 필요할 때가 있기에 공부할 겸 정리를 해보았다.

 

 

1. Type에서는 유니온 타입, 인터섹션 타입, 튜플 타입을 사용할 수 있다.

type AnimalType1 = { animal: 'Dog' };
type AnimalType2 = { age: number; name: string; };

// intersection
type IntersectionAnimal = AnimalType1 & AnimalType2;

// union
type UnionAnimal = AnimalType1 | AnimalType2;

// tuple
type TupleAnimal = [number, string];

union 연산자를 사용한 타입의 경우에는 extends, implements 키워드 사용이 불가능하다.

 

 

2. Type과 Interface는 확장하는 방법이 다르다.

type AnimalType = {
    animal: "Dog";
    age: number;
    name: string;
};

type AnimalBirth = AnimalType & {
    birth: number;
};

type의 경우 &(앰퍼샌드)로 상속한다.

 

interface AnimalInterface {
    animal: "Dog";
    age: number;
    name: string;
}

interface AnimalBirth extends AnimalInterface {
    birth: number;
};

interface의 경우 extends로 확장한다.

 

 

3. Interface는 선언 병합이 가능하다.

선언 병합(Declaration Merging)이란 새로운 속성을 추가하기 위해 같은 이름을 갖는 인터페이스를 선언하는 것이다.

 

interface AnimalInterface {
    animal: "Dog";
    age: number;
    name: string;
}

interface AnimalInterface {
    birth: number;
}

const animal: AnimalInterface = {
    animal: "Dog",
    age: 1,
    name: "choco",
    birth: 230113,
};

중복된 인터페이스는 나중에 자동으로 병합된다.

 

type AnimalType = {
    animal: "Dog";
    age: number;
    name: string;
};

type AnimalType = {
    birth: number;
}; // Error: Duplicate identifier 'AnimalType'

type의 경우 에러가 발생한다.

'Typescript' 카테고리의 다른 글

[Typescript] File은 단순히 타입이 아니다.  (0) 2025.03.19
[Typescript] Never에 대해서  (0) 2023.03.17
useRef에 타입 주기  (0) 2022.12.12
Comments