SooJungChae / TIL

Today I Learned
MIT License
1 stars 2 forks source link

[typescript] interface vs type #86

Closed SooJungChae closed 2 years ago

sbjang123456 commented 2 years ago

6번과 같은 형태는 type 만 사용할 수 있는 건가요!?!

SooJungChae commented 2 years ago

6번과 같은 형태는 type 만 사용할 수 있는 건가요!?!

예에~!! type 만 사용할 수 있습니다 😏

sbjang123456 commented 2 years ago

그럼 typescript에서 type은 객체형태라고 봐도 되나요? 그리고 저 형태를 활용해서 공통으로 쓰는 타입들을 몇가지의 공통 타입으로 정의한 뒤, 다른 곳에서 여기저기 써도 될까요? 예를들면

type CommonBoard = {
  id: number,
  title: string,
  author: string
}

interface BannerBoard {
  bannerId: CommonBoard['id'];
  bannerTitle: CommonBoard['title'];
  content: string;
}

interface NoticeBoard {
  noticeId: CommonBoard['id'];
  noticeTitle: CommonBoard['title'];
  status: number;
}

간단히 예를 들었지만, 기본적인 게시판에서도 공통으로 쓰는 타입들은 고정적일 것 같아서 이렇게도 써도 될지 문의드립니다.

SooJungChae commented 2 years ago

그럼 typescript에서 type은 객체형태라고 봐도 되나요? 그리고 저 형태를 활용해서 공통으로 쓰는 타입들�을 몇가지의 공통 타입으로 정의한 뒤, 다른 곳에서 여기저기 써도 될까요?

@sbjang123456 네, 너무 좋은 예시같아요!! 공통적으로 사용하는 type 을 프로퍼티로 접근하면 수정할 때도 한군데에서만 해도 되니 더 효율적이겠네요. 저도 게시판 같은 경우 id 값을 string 으로 해야할지 number 로 해야할지 헷갈렸는데 이런 방식이면 깔끔하게 재사용 가능할 것 같습니다