IT/TypeScript

type과 interface의 공통점과 차이점

솔B 2022. 4. 11. 23:08

확장

interface -extends를 사용

type - &를 사용

interface Student {
	major: string
    studentId: number
}

const mike: Student = {
	major: 'computer',
    studentId: 202212011
}

type Student = {
	major: string
    studentId: number
}

const mike: Student = {
	major: 'computer',
    studentId: 202212011
}

 

선언적 확장

interface에서는 새로운 속성을 추가하기 위해 같은 이름을 선언할 수 있지만, type은 선언적 확장이 불가능하다.

interface Student {
	major: string
    studentId: number
}

interface Student {
	score: number
}

const mike: Student = {
	major: 'computer',
    studentId: 202212011,
    score: 99
}

type Student = {
	major: string
    studentId: number
}

type Student = { // error
	score: number
}

 

interface는 객체에만 사용 가능

interface StudentInterface {
	major: string
}

type StudentType = {
	major: string
}

type StudentTypeString = string
type StudentTypeNumber = number

interface X extends string {} // 불가능

 

computed value의 사용

type은 가능하지만 interface는 불가능하다.

type names = 'firstName' | 'lastName'

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

const gildong: NameTypes = { firstName: 'gildong', lastName: 'hong' }

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

 

결론,

interface와 type을 확장할 때 interface는 속성 간에 충돌을 해결하기 위해 단순한 객체 타입을 만든다. interface는 객체의 타입을 만들기 위한 것이고 객체만 오기 때문에 단순히 합치면 된다. type은 재귀적으로 순회를 하면서 속성을 merge 하는데 이때 일부가 never이 나오면서 merge가 안 될 수 있다. type 속성을 merge 할 때는 주의해야 한다. 객체에만 쓴다면 interface를 쓰는 것이 좋다.

 

interface들을 합성할 경우 캐시가 되지만 type은 아니다. type 합성은 합성에 대한 유효성을 판단하기 전에, 모든 구성요소에 대한 타입을 체크하므로 컴파일 시에 상대적으로 성능이 좋지 않다고 한다.