STUDY/Typescript

[Typescript] type vs interface

_JJ_ 2024. 11. 18. 10:11

 

진행 중인 리액트 프로젝트를 타입스크립트로 바꾸고 있는데,

객체의 타입을 줄 때 어떤건 type으로 주고, 어떤건 interface로 주기에 무슨 차이인가 알아보게 되었다.


확장

interface

interface Person {
  name: string;
  age: number;
}

interface Student extends Person {// 확장(상속)
  school: string;
}

const hello: Student = {
  name: 'hello',
  age: 11,
  school: 'world'
}

 

type

type Person {
  name: string;
  age: number;
}

type Student = Person & { // 확장(상속)
  school: string;
}

const hello: Student = {
  name: 'hello',
  age: 11,
  school: 'world'
}

 

 

선언적 확장(Declaration Merging)

interface

같은 이름의 interface를 선언하면 자동으로 확장된다.

라이브러리를 사용하는 상황에서 추가적으로 타입의 속성들을 선언할 때 유용하다.

interface Person {
  name: string;
  age: number;
}

interface Person { // 선언적 확장
  school: string;
}

const hello: Person = {
  name: 'hello',
  age: 11,
  school: 'world'
}

 

type

선언적 확장이 불가능하다.

 

 

자료형(type)

interface

객체(object) 타입을 설정할 때 사용할 수 있으며, 원시 자료형에는 사용할 수 없다.

단순 원시값이나 튜플(Tuple), 유니언(Union) 타입을 선언할 때는 type을 사용하는 것이 좋다.

type Name = string;
type Age = number;
type Person = [string, number, boolean];
type NumberString = string | numberlike;

type Person = {
  name: string,
  age: number,
  gender: string;
}

 

type은 모든 타입을 선언할 때, interface는 객체에 대한 타입을 선언할 때만 사용할 수 있다.

확장 불가능한 타입을 선언하고 싶으면 type, 확장 가능한 타입을 선언하고 싶다면 interface

 

 

reference

https://velog.io/@wlwl99/TypeScript-type%EA%B3%BC-interface%EC%9D%98-%EC%B0%A8%EC%9D%B4

https://tecoble.techcourse.co.kr/post/2022-11-07-typeAlias-interface/