[TIL 58] Typescript | type alias와 interface의 차이

sunny·2021년 7월 6일
0
post-thumbnail

Typescript에서 타입을 지정해줄 수 있는 방법은 type alias, interface가 있다. 사용방법과 둘의 차이를 알아보자! 🧐

type alias, interface 사용방법

//type alias
type TFruits = {
  id: number;
  name: string;
};

//interface
interface IFruits {
  id: number;
  name: string;
}

//type alias 사용
const typeFruits: TFruits = {
  id: 2,
  name: 'banana',
};

//interface 사용
const interfaceFruits: IFruits = {
  id: 1,
  name: 'orange',
};

type alias, interface의 차이점

interface는 재정의가 가능하다.

interface의 경우 같은 이름으로 재정의가 가능하다.

interface IFruits {
  id: number;
  name: string;
}

interface IFruits {
  price: number;
}

const interfaceFruits: IFruits = {
  id: 1,
  name: 'orange',
  price: 2000,
};

type alias는 유니온, 튜플도 타입으로 지정할 수 있다.

type UnionType = string | null;

// string
type StringType = 'hi' | 'namsun';

// number
type NumType = 1 | 2 | 3 | 4 | 5;

// object
type ObjectType = { name: 'orange' } | { price: 2000 };

// function
type FuncType = (() => number) | (() => void);

// tuple
type TupleType = [string, boolean];
const namsun: TupleType = ['dev', true];

확장성에서 차이가 있다.

  • interface 끼리는extends, implements 키워드를 사용할 수 있다.
  • type alias 끼리는 extends, implements 키워드를 사용할 수 없다.
  • interface extends type alias는 가능하다.
  • class implements type alias, interface는 가능하다.
  • class extends type alias, interface는 불가능하다.
type TPerson = {
  name: string | undefined;
  age: number | undefined;
}

interface IPerson {
  name: string | undefined;
  age: number | undefined;
}

interface IPerson extends TPerson {}

class PersonImpl implements TPerson {
  name: string | undefined;
  age: number | undefined;
}

class PersonImpl implements IPerson {
  name: string | undefined;
  age: number | undefined;
}

class PersonChild extends TPerson = {} //error

interface는 새 이름을 생성한다.

다음과 같은 코드가 있다고 가정해보자.

type TFruits = {
  name: string;
};

interface IFruits {
  name: string;
}
const typeFruits = (fruit: TFruits): TFruits => {};
const interfaceFruits = (fruit: IFruits): IFruits => {};

typeFruits와 interfaceFruits 둘 다 정의한 타입의 attribute가 없으므로 에러가 나는 코드다. 둘의 에러메세지를 비교해보자.

typeFruits

interfaceFruits

type alias는 type TFruits = { name: string; };
가 나오고, interface는 interface IFruits가 나온다. 인터페이스는 어디서나 사용되는 새로운 이름을 만들기 때문이다. 이런 이유로 만약에 type alias에 오류가 생기면 오류메시지에는 type alias가 사용되지 않을 것이다.

profile
blog 👉🏻 https://kimnamsun.github.io/

0개의 댓글