타입스크립트 타이핑하기

Dengo·2022년 5월 6일
0

TypeScript

목록 보기
1/2
post-thumbnail

두가지의 방법이 있다.

  • Type Alias
  • Interface

각각 한번 간단히 알아보자

Type Alias

type NewsFeed = {
  id : number;
  time_ago : string;
  title : string;
  url : string;
  user : string;
  content : string;
  comments_count : number;
  points : number;
  read : boolean;
}

이런식으로 생겼다.
NewsFeed뿐만 아니라 NewsDetail도 있어서 두 개에서 공통된 요소가 있다면 하나로 묶어지고 싶어지지 않은가?

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

type NewsFeed = News & {
  comments_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;
  points : number;
  read : boolean;
}

타입 얼리어스 방법으로 하면 Union 타입을 상속 받을 수가 있다.

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

추가로 이런방식으로 읽기 전용 임을 선언 할 수 있고,
read? 부분은 read에 값이 들어갈수도, 안들어갈수도 있어서 null을 허용한다는 의미에서 ?를 붙여 선언 가능하다.

profile
Software Engineer (전산쟁이)

0개의 댓글