본문 바로가기

[TypeScript] type vs interface (차이점을 중심으로)

by mugglim 2022. 5. 31.

TL;DR

  • 상속 시, type은 동일한 속성의 값 타입을 오버로딩 하며 interface는 서브 타입 관계를 확인한다.
  • type은 모든 타입으로 확장 할 수 있으며, interface는 object 형태의 타입만 상속받을 수 있다. (class, interface, typeof object)
  • type은 선언 병합을 허용하지 않으며, interface는 선언 병합을 허용한다.
    (단, interface에서 선언 병합 시 동일한 속성이 있다면, 반드시 값 타입이 같아야 한다.)

용어

  • A >: B : A는 B의 슈퍼타입이다. (= B는 A의 서브타입이다.)

1. 상속 시 동일한 속성이 존재하는 경우

  • type은 상속 시, 동일한 프로퍼티에 대해 오버로딩한다.
  • interface는 상속 시, 부모 interface의 속성 타입 >: 자식 interface의 속성 타입 관계를 만족해야 한다.
// type 상속
type Animal = {
  age: string;
}

type Dog = Animal & {
  age : string | number; // no-error (overloading)
}

// interface 상속
interface Animal  {
  age : string;
}

interface Dog extends Animal {
  age : string | number; // error! 
}

interface 상속에서 에러가 발생하는 이유는 "Dog의 age의 값 타입 >: Animal의 age 값 타입" 관계를 갖기 때문이다.

2. 상속을 받을 수 있는 타입

  • type은 모든 타입을 상속 받을 수 있다.
  • interface는 object 형태의 타입만 상속받을 수 있다. (class, interface, typeof object)
type T = <all type> [ |, & ] <all type>

interface I extends <class, typeof object, interface> {
    // ..
}

3. 선언 병합의 경우

  • type은 선언 병합을 허용하지 않는다.
  • interface는 선언 병합을 허용한다. (단, 동일한 속성이 있는 경우 반드시 값 타입이 같아야 한다.)
// error
type Animal {
  name : string;
}
type Animal {
  age : number;
}

// no-error
interface Animal {
  name : string;
}

interface Animal {
  age: number;
}
// no-error
interface Animal {
  name : string;
}

// no-error (같은 값 타입)
interface Animal {
  name : string;
}

// error (다른 값 타입)
interface Animal {
  name : string | number;
}

Ref

  • Chapter 5. Class and Interface, Programming TypeScript
  • Item 13: Know the Differences Between type and interface, Effective TypeScript

댓글