본문으로 건너뛰기

아이템13

타입과 인터페이스의 차이점 알기

  • 타입스크립트의 명명된 타입을 정의하는 방법은 두가지 이다.
  • 첫번째는 type 선언문, 두 번째는 interface 문이다.

공통점

  • 타입의 기본 동작
type Tname = {
name: string;
};

interface Iname {
name: string;
}

const typeName: Tname = {
name: "James",
};

const interfaceName: Iname = {
name: "James",
};
  • 인덱스 시그니처
type TypeIndexSignature = {
[key: string]: string;
};

interface InterfaceIndexSignature {
[key: string]: string;
}
  • 함수 타입 정의
type TypeFunction = {
(x: number): number;
};

interface InterfaceFunction {
(x: number): number;
}

const typeFunction: TypeFunction = (x) => 0;

const interfaceFunction: InterfaceFunction = (x) => 0;
  • 제네릭
type TypeGeneric<T> = {
first: T;
};

interface InterfaceGeneric<T> {
first: T;
}
  • 타입 확장
type TypeExtendedInterfaceGeneric<T> = InterfaceGeneric<T> & { second: T };

interface InterfaceExtendedTypeGeneric<T> {
second: T;
}
  • 클래스 구현
class ClassTypeGeneric<T> implements TypeGeneric<T> {
first: T;

constructor() {
this.first = Object();
}
}

class ClassInterfaceGeneric<T> implements InterfaceGeneric<T> {
first: T;

constructor() {
this.first = Object();
}
}

차이점

  • 유니온 개념의 유무 : type에는 유니온 타입이 있지만, interface에는 유니온 인터페이스가 없다.
type TypeAorB = "a" | "b";

interface InterfaceAorB {
// ...?
}
  • 튜플과 배열 타입의 간결한 표현 type 키워드를 이용하면 튜플과 배열 타입도 간결하게 표현할 수 있다. interface를 사용하게 되면 유사하게 만들 수 있으나 튜플의 프로토타입 체인 상에 있는 메서드들을 사용할 수 없다.
interface Triple {
0: number;
1: number;
2: number;
length: 3;
}

const triple: Triple = [0, 1, 2];
  • 보강 기능 : interface선언 병합을 통해 확장이 가능하다.
interface IState {
name: string;
capital: string;
}

interface IState {
population: number;
}

const wyoming: IState = {
name: "Wyoming",
capital: "Cheyenne",
population: 500,
};