TypeScript _ Type alias vs. Interface

LOOPY·2021년 8월 18일
post-thumbnail

Type alias vs interface

  • function
// type alias
type EatType = (food: string) => void;

// interface
interface IEat {
  (food: string): void;
}
  • array
// type alias
type PersonLit = string[];

// interface
interface IPersonList{
  [index: number]: string;
}
  • intersection
interface ErrorHandling{
  success: boolean;
  error?: {message: string};
}
interface ArtistsData{
  artists: {name: string}[];
}

// type alias
type ArtistsResponseType = ArtistsData & ErrorHandling;

// interface
interface IArtistsResponse extends ArtistsData, ErrorHandling{}

let art: ArtistsResponseType;
let iar: IArtistsResponse;
  • union types
interface Bird{
  fly(): void;
  layEggs(): void;
}
interface Fish{
  swim(): void;
  layEggs(): void;
}

type PetType = Bird | Fish;

interface IPet extends PetType{} // error
class Pet implements PetType{} // error
  • Declaration Merging: interface에서 같은 이름으로 다른 곳에서 속성을 정의하면 사용할 때에는 자동으로 해당 속성이 합쳐지는 꼴이 됨 (alias는 불가능)
profile
2년차 프론트엔드 개발자의 소소한 기록을 담습니다 :-)

0개의 댓글