타입스크립트에서 명시적으로 타입을 정의해 주는 방법은 크게 Type 또는 Interface를 사용하는 방법이 있다.

하지만 두가지 방식에는 차이점이 있다.

공통점


type BirdType = {
  wings: 2;
};

interface BirdInterface {
  wings: 2;
}

const bird1: BirdType = { wings: 2 };
const bird2: BirdInterface = { wings: 2 };

///

const bird3: BirdInterface = bird1;

type Owl = { nocturnal: true } & BirdType;
type Robin = { nocturnal: false } & BirdInterface;

차이점


Type은 타입들을 교차하여 타입을 확장시키는반면, Interface는 키워드가 있다.

<aside> 💡 Interface의 키워드 때문에 에러 메시지가 더 명확하게 나오는게 아닐까

</aside>

1. 에러메시지

Interface를 사용하는 경우 Type을 사용할 때 보다 더욱 명확한 에러 메시지를 확인 할 수 있다.

type Owl = { nocturnal: true } & BirdType;
type Robin = { nocturnal: false } & BirdInterface;

interface Peacock extends BirdType {
  colourful: true;
  flies: false;
}
interface Chicken extends BirdInterface {
  colourful: false;
  flies: false;
}

let owl: Owl = { wings: 2, nocturnal: true };
let chicken: Chicken = { wings: 2, colourful: false, flies: false };

예시 코드의 에러메시지를 보면 ‘Chicken’의 에러가 정확하게 출력되는걸 확인 할 수 있다.

Type 'Chicken' is not assignable to type 'Owl'.
  Property 'nocturnal' is missing in type 'Chicken' but required in type '{ nocturnal: true; }'.
Type 'Owl' is missing the following properties from type 'Chicken': colourful, flies
Duplicate identifier 'Puppy'.
Duplicate identifier 'Puppy'.

2. 확장의 여부