Node.js & TypeScript

TypeScript type과 interface의 공통점과 차이점

martinooo 2022. 11. 18. 14:47
728x170

🤳TypeScript type과 interface의 공통점과 차이점 


interface PeopleInterface {
  name: string
  age: number
}

const me1: PeopleInterface = {
  name: 'yc',
  age: 34,
}

type PeopleType = {
  name: string
  age: number
}

const me2: PeopleType = {
  name: 'yc',
  age: 31,
}
  • type과 interface는 객체의 타입을 지정하는 공통점이 있다. 

👀TypeScript type과 interface의 차이점


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
}
  • 확장하는 방식에서 차이가 있습니다.
    • 선언적 확장이 가능하다. 

  • interface 병합을 해서 사용이 가능하다. 
  • type 병합이 안된다 

  • interface는 객체에만 사용이 가능하다. 
interface FooInterface {
  value: string
}

type FooType = {
  value: string
}

type FooOnlyString = string
type FooTypeNumber = number

// 불가능
interface X extends string {}
  • 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
}

👏성능을 위해서는 interface를 사용하는 것이 좋다. 

라는 취지의 문서를 본적이 있는데, 한번  읽어 보는것을 추천해드립니다.

https://github.com/microsoft/TypeScript/wiki/Performance#preferring-interfaces-over-intersections

Interfaces create a single flat object type that detects property conflicts, which are usually important to resolve! Intersections on the other hand just recursively merge properties, and in some cases produce never.

 

그리드형