Type Aliasing vs Interface

eeensu·2023년 8월 4일
0

typescript

목록 보기
11/22
post-thumbnail

Type Aliasing 과의 작성법 차이

  1. function을 만들 때
type EatType = (food: string) => void;

interface IEat {
    (food: string): void;
}
  1. Array를 만들 때
type ArrayType = Array<string>; 
// 또는
type ArratType2 = string[];

interface IArray {
    [index: number]: string;
}
  1. intersection을 만들 때
type ArtistsResponseType = ArtistsData & ErrorHandling;

interface IArtistsResponse extends ArtistsData, ErrorHandling {
 	~ 
}
  1. union type을 만들 때
type PetType = Bird | Fish;

// inteface는 유니온 타입을 표현하기 어렵다.
  1. Declaration Merging
    Declaration Merging은 여러번의 선언으로 같은 이름의 인터페이스를 확장하거나 수정할 수 있는 기능이다. interface 에서만 할 수 있는 기능이다.
interface Person {
 	name: string; 
}

interface MyInterface {
 	age: number; 
}

const person = { 
  name: 'Mark', 
  age: 24 
};

일반적으로, 구조적인 타입을 정의하거나 객체의 형식을 선언할 때는 interface를, 유니온 타입, 인터섹션 타입 등을 사용하거나 복잡한 타입 변환을 처리할 때는 type을 선호하는 경향이 있다. 하지만 어떤 상황에서도 이 두 가지를 함께 사용하여 코드를 더 효율적으로 작성하는 것이 가능하다.


type과 interface를 사용하는 객관적인 기준은 모호하다. 각자의 기준을 나름대로 정하여 사용하는 것이 유지보수에 좋다. 필자는 '속성'이 그 '속성'으로서 목적이나 존재가치가 명확하면 interface를 사용하고, 그렇지 않고 어떤 대상을 가르킬 뿐이라든가 혹은 별명으로서만 존재한다면 type aliasing을 하는 것을 추천한다.

profile
안녕하세요! 26살 프론트엔드 개발자입니다! (2024/03 ~)

0개의 댓글