TypeScript(type alias vs interface)

Dev_Go·2022년 7월 11일
0

TypeScript Essentials

목록 보기
22/24
post-thumbnail

type alias vs interface


function

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

// interface
interface IEat {
  (food: string): void;
}

array

// type alias
type PersonList = 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 TS2312: An interface can only extend an object type or intersection of object types with statically known members.

class Pet implements PetType {} // error TS2422: A class can only implement an object type or intersection of object types with statically known members.

Declaration Merging - interface

기존에 있는 인터페이스가 있는데 추가해야될 때 Declaration Merging을 사용한다.

interface MergingInterface {
  a: string;
}

interface MergingInterface {
  b: string;
}

let mi: MergingInterface;
mi.

mi.을 하면 a도 나오고 b도 나온다. interface의 이름이 같으면 합쳐진다, 이를 Merging이라고 한다.


Declaration Merging - type alias

type MergingType = {
  a: string;
};

type MergingType = {
  b: string;
};

type alias는 똑같은 이름으로 작성하면 오류가 뜬다.
Declaration Merging은 interface만 가능하다.

profile
프론트엔드 4년차

0개의 댓글