본문 바로가기

개인공부/프론트엔드

TypeScript: typeAlias vs interface

반응형

타입스크립트에서는 타입을 명시하기위해서 두가지 방법을 사용한다. 문법적으로 비슷하지만 약간다르고 지원하는 내용도 차이가 있다.

다음과 같은 News와 NewsFeed 타입으로 명시하겠다.

 

typeAlias

type News = {
	id: number;
    time_ago: string;
    title: string;
    url: string;
    user: string;
    content: string;
}

type NewsFeed = & News {
	commnets_count: number;
    points: number;
    read?: boolean;
}

 

interface

interface News {
  id: number;
  time_ago: string;
  title: string;
  url: string;
  user: string;
  content: string;
}

interface NewsFeed extends News {
  comments_count: number;
  readonly points: number;
  read?: boolean;
}

 

  interface typeAlias
스코프 X O
readOnly O X
상속받는 방법 extends &
다중 타입 X (지원안함) 유니온 지원

 

여기서 다중타입이란??

const container: HTMLElement | null = document.getElementById('root');

이와 같이 특정 변수가 어떤타입으로 반환받을지 선택이 여러개있는 경우를 말한다. typeAlias 는 지원하지만 interface는 유니온을 적용할 수 없다. 적절하게 사용하자. 또한 readOnly라는 기능을 인터페이스에서 제공하기 때문에 외부에서 변수를 변경할 수 없게한다. (JavaScriptd에서도 가능하지만 다소 복잡한 것으로 알고 있다.)

반응형

'개인공부 > 프론트엔드' 카테고리의 다른 글

javascript: 상속 (extends)  (0) 2021.06.27
TypeScript: 제너릭  (0) 2021.06.27
클로저  (0) 2021.06.21
JavaScript push를 이용해서 렌더링하기.  (0) 2021.06.09
XML HttpRequest ajax  (0) 2021.06.06