TypeScript

[TypeScript] interface와 Type Alias의 차이

sungtt 2022. 5. 9. 01:54

interface와 Type Alias의 차이

interface중복 선언 시 각 요소들이 병합된다.

Type Alias중복 선언 시 오류가 난다.


interface 병합 시😄

// 인터페이스 Button 정의
interface ButtonInterface {
  onInit():void;
  onClick():void;
}

// 인터페이스 Button 중복 정의
interface ButtonInterface {
  onChange():void;
}

//위 코드는 아래와 같다.
interface ButtonInterface {
  onInit():void;
  onClick():void;
  onChange():void;
}

 

Type Alias 병합 시😱

type ButtonType = {
  onInit():void;
  onClick():void;
}

// [오류]
// 'ButtonType' 식별자가 중복되었습니다.
type ButtonType = {
  onChange():void;
}

 

무엇을 지양해야하는가?

Type Alias보다는 확장성이 더 뛰어난 Interface를 지양하자.