본문 바로가기

Front-end/Typescript

type vs interface

차이점

1. 확장하는 방법

// interface
interface PeopleInterface {
  name: string
  age: number
}

interface StudentInterface extends PeopleInterface{
  school: string
}
// type
type PeopleType = {
  name: string
  age: number
}

type StudentType = PeopleType & {
  school: string
}

2. 선언적 확장

  • interface에서 할 수 있는 대부분의 기능은 type에서 가능
  • type은 새로운 속성을 추가하기 위해 같은이름으로 선언할 수 없음
  • interface는 항상 선언적 확장이 가능
// interface
interface window {
  title: string
}

interface Window {
  ts: TypeScriptAPI
}
// type
type Window = {
  title: string
}

type Window = {
  ts: TypeScriptAPI
}
// Error: Duplicate identifier 'Window'

4. interface는 객체에만 사용 가능

interface FooInterface {
  value: string
}

type FooOnlyString = string

5. computed value의 사용

  • type은 가능
  • interface는 불가능
type names = 'firstName' | 'lastName'

type NameTypes = {
  [key in names]: string
}

const yc: NameTypes = { firstName: 'hi', lastName: 'yc' }

interface NameInterface {
  // error
  [key in names]: string
}

TypeScript 팀의 의도

TypeScript 팀은 개방-폐쇄 원칙에 따라 확장에 열려있는 JavaScript 객체의 동작 방식과 비슷하게 연결하도록 Interface를 설계했습니다.

그래서 TypeScript 팀은 가능한 Type Alias보단 Interface를 사용하고, 합 타입 혹은 튜플 타입을 반드시 써야 되는 상황이면 Type Alias를 사용하도록 권장하고 있습니다.

 

참고자료

https://medium.com/humanscape-tech/type-vs-interface-%EC%96%B8%EC%A0%9C-%EC%96%B4%EB%96%BB%EA%B2%8C-f36499b0de50

'Front-end > Typescript' 카테고리의 다른 글

Enum  (0) 2022.11.23
Typescript Core  (0) 2022.11.23