Dev

Type Alias는 Anonymous Interface다.

Jun Park 🎵 2023. 12. 6. 01:44

삘 받은 김에 질러버리는 글. 일전에 Type Alias가 Interface의 대부분 기능을 지원하니 Type Alias를 더 적극적으로 사용하자는 글을 썼다. 이후 열심히 그렇게 사용하다가 갑자기 뇌리를 스친 것이 있으니...

// 1. 원래는 이렇게 하던 것을
interface User {
  name: string;
  age: number;
}
type Viewer = User;

// 2. 이렇게 단축했다고 생각하면 어떨까
type Viewer = {
  name: string;
  age: number;
};

 

 

1번 type 선언은 User Interface의 Type Alias인 Viewer를 선언한다.

2번 type 선언은 임의의 Interface의 Type Alias인 Viewer 선언한 것인데 이 Interface는 Anonymous Interface다.

 

1번이든 2번이든 Viewer는 Type Alias로 Interface를 참조했기 때문에 Declaration Merging의 대상이 될 수는 없다.

 

이런 관점으로 바라보면 어떤 대상의 추상적인 명세를 선언할 때는 Interface over Type Alias 원칙이 유효하다.

'Dev' 카테고리의 다른 글

비전공자 출신 프로그래머 기준 책 추천/리뷰  (2) 2024.02.05
2023년 2분기 회고  (0) 2023.06.30
WebRTC 원리 쉬운 설명  (0) 2023.04.24
2023년 1분기 회고  (0) 2023.04.06
Type (Alias) over Interface  (0) 2023.04.05