[interface vs. type ] 비교

Yerim·2023년 5월 22일
1

개념정리

목록 보기
1/1
post-thumbnail

팀장님이 interfacetype 의 차이에 대해 질문하셨다.

평소에 Typescript로 업무를 진행하면서,
타입을 지정할 때 interface 로 선언하는 것과 type 으로 선언하는 것의
차이에 대해 궁금했지만, 둘 다 섞어서 사용해도 작업하는 데에 지장이 없었다.

그렇게 궁금증만 남은 채 다시 바쁜 업무 속으로 돌아갔다.

즉시 찾아보거나, 바쁘면 메모해 두었다가 찾아봤어야 했는데..
이렇게 잊혀진 것이 한 두개가 아니다 ㅠ_ㅠ

이 참에 확실히 해서 정리해보려고 한다..!


type vs. interface

먼저, typeinterface 의 사용법은 다음과 같다.

interface Human {
  name: string;
  age: number;
}

type Human = {
  name: string;
  age: number;
}

1. 확장 방식이 다르다.

interface PeopleInterface {
  name: string;
  age: number;
}

interface StudentInterface extends PeopleInterface {
  school: string;
}
type PeopleType = {
  name: string;
  age: number;
}

type StudentType = PeopleType & {
  school: string;
}

2. interface 는 "선언 병합"이 가능하지만, type 은 그렇지 않다.

선언 병합이란,
동일한 이름으로 여러 번 선언하면 컴파일 시점에 자동으로 병합되어 확장되는 것이다.

interface Window {
  title: string;
}

interface Window {
  ts: import("typescript");
}

declare function getWindow(): Window;

const window = getWindow();
const src = 'const a = "Hello World"';
window.ts.transpileModule(src, {});

interface의 경우 위 코드가 정상 작동하지만,
type의 경우 에러가 발생한다.

type Window = {
  title: string;
}

type Window = {
  ts: import("typescript");
}

// Error: Duplicate identifier 'Window'.

3. interface 는 객체에만 사용 가능하다.

interface FooInterface {
  value: string;
}

type FooType = {
	value: string;
}

type FooOnlyString = string;
type FooTypeNumber = number;

interface X extends string {} // 불가능

4. computed value의 사용 - type만 가능하다.

type names = 'firstName' | 'lastName';

type NameTypes = {
  [key in names]: string; // Good
}

const yc: NameTypes = {firstName: 'hi', lastName: 'yc'}

interface NameInterface {
  [key in names]: string; // Error
}

참고
1. https://yceffort.kr/2021/03/typescript-interface-vs-type
2. https://medium.com/humanscape-tech/type-vs-interface-%EC%96%B8%EC%A0%9C-%EC%96%B4%EB%96%BB%EA%B2%8C-f36499b0de50

profile
안녕하세요. 프론트엔드 개발자입니다.

0개의 댓글