팀장님이 interface
와 type
의 차이에 대해 질문하셨다.
평소에 Typescript로 업무를 진행하면서,
타입을 지정할 때 interface
로 선언하는 것과 type
으로 선언하는 것의
차이에 대해 궁금했지만, 둘 다 섞어서 사용해도 작업하는 데에 지장이 없었다.
그렇게 궁금증만 남은 채 다시 바쁜 업무 속으로 돌아갔다.
즉시 찾아보거나, 바쁘면 메모해 두었다가 찾아봤어야 했는데..
이렇게 잊혀진 것이 한 두개가 아니다 ㅠ_ㅠ
이 참에 확실히 해서 정리해보려고 한다..!
먼저, type
과 interface
의 사용법은 다음과 같다.
interface Human {
name: string;
age: number;
}
type Human = {
name: string;
age: number;
}
interface PeopleInterface {
name: string;
age: number;
}
interface StudentInterface extends PeopleInterface {
school: string;
}
type PeopleType = {
name: string;
age: number;
}
type StudentType = PeopleType & {
school: string;
}
선언 병합이란,
동일한 이름으로 여러 번 선언하면 컴파일 시점에 자동으로 병합되어 확장되는 것이다.
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'.
interface FooInterface {
value: string;
}
type FooType = {
value: string;
}
type FooOnlyString = string;
type FooTypeNumber = number;
interface X extends string {} // 불가능
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