TypeScript

type alias, interface

Summer.dev 2023. 9. 3. 16:58

요약 

Type Alias는 모든 타입을 선언할 때 사용할 수 있고

Interface는 객체에 대한 타입을 선언할 때 사용될 수 있다.

차이점은 확장 가능 여부이며

확장 불가능한 타입 선언시 Type Alias

확장 가능한 타입 선언시 Interface를 사용한다.

 

설명

사실 제일 최근 프로젝트를 하면서 type alias는 모든 타입을 선언할 때 사용할 수 있어서

거의 모든 객체 데이터 타입을 type alias로 설정해주었습니다.

//interface
interface Person {
  name: string,
  age?: number
}

const person = {} as Person;
person.name = 'Kim';
person.age = 25;
person.address = 'Seoul'; // Error

// type alias
type Person = {
  name: string,
  age?: number
}

const person = {} as Person;
person.name = 'Kim';
person.age = 25;
person.address = 'Seoul'; // Error

위 코드와 같이 interface와의 차이점을 크게 느끼지 못했기 때문입니다.

 

typescript 공식문서에 따르면 type aliasinterface의 가장 큰 차이점은

type alias 는 새 프로퍼티를 추가할 수 없고

interface 는 항상 확장 될 수 있다는 점입니다.

아래는 예시 코드 입니다.

interface 는 Person 이라는 같은 식별자를 사용해도 선언 병합이 가능하지만

type alias 는 에러를 발생 시킵니다.

 

공식문서에서는 type 사용이 필요하지 않는 이상 interface 사용을 더 권장하고 있습니다.

타입스크립트 핸드북에서도 확장이 용이해야한다는 프로그래밍 원칙에 따라 객체 타입 선언시 interface 사용을 권장하고있습니다.

 

Ref

https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#differences-between-type-aliases-and-interfaces

 

Documentation - Everyday Types

The language primitives.

www.typescriptlang.org

 

https://joshua1988.github.io/ts/guide/type-alias.html#%ED%83%80%EC%9E%85-%EB%B3%84%EC%B9%AD-type-aliases

 

타입 별칭 | 타입스크립트 핸드북

타입 별칭 (Type Aliases) 타입 별칭은 특정 타입이나 인터페이스를 참조할 수 있는 타입 변수를 의미합니다. 예를 들면 아래와 같습니다. 위와 같이 string, number와 같은 간단한 타입 뿐만 아니라 inter

joshua1988.github.io

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

 

interface vs type alias

what is the difference between interface and type alias? typescript…

tecoble.techcourse.co.kr