[TypeScript] type과 interface

Minha Ahn·2023년 7월 21일
1

✅타입 선언 방법

타입스크립트에서 타입을 선언하는 방법은 2가지가 있다.
type으로 선언하는 방법과 interface로 선언하는 방법이다.

✅type alias vs interface

내가 느끼기에 type alias와 interface의 기능은 대부분 비슷한 것 같다.

🔎타입 선언 방법

  • type alias로 선언하는 방법
type Type1 = {
  num: number
}

const data1: Type1 = { num: 1 }
  • interface로 선언하는 방법
interface Interface1 {
  num: number
}

const data2: Interface1 = { num: 2 }

🔎type alias와 interface의 공통적 특징

  • 객체 타입 선언 가능
  • 함수 타입 선언 가능
  • 확장 가능
    • type alias : &를 사용해 intersection
    • interface : extends를 사용해 inheritance

🔎type alias만의 특징

  • 유니온 타입(Union Type)이 가능하다.
type Fruit = 'apple' | 'banana'
type Vegetable = 'carrot' | 'tomato' | 'onion'
type Food = Fruit | Vegetable

const food: Food = 'apple'
  • 튜플 타입(Tuple Type)이 가능하다.
type Student = [name: string, age: number, major: string]

const student: Student = [ 'AA', 20, 'Computer Engineering']

🔎interface만의 특징

  • 여러 번 선언 가능(자동 병합) = 선언적 확장
  • 객체에서만 사용 가능

🔎type alias VS interface

  • interfce 합성할 경우 캐시가 되지만 type은 그렇지 못함.
  • type 합성의 경우 모든 구성 요소에 대한 type을 체크하므로 컴파일 시에 상대적으로 성능이 좋지 않다고 함.

💡결론

공식문서에서는 기본으로 interface를 사용하고 type의 특성이 필요한 경우에만 type을 사용하라고 적혀있다.

profile
프론트엔드를 공부하고 있는 학생입니다🐌

0개의 댓글