공식문서
Documentation - Everyday Types
The language primitives.
www.typescriptlang.org
타입스크립트에서 타입을 표현하기 위해 Type 또는 Interface를 사용합니다. 이때 두 방식은 거의 비슷한데요. 어떤 경우에는 Type을 사용하는 것이 좋고 어떤 경우에는 Interface를 사용하는 것이 더 좋을지 궁금해져 이에 대해 알아보았습니다.
type
type은 모든 타입을 표현할 수 있습니다. 객체 타입, 유니온 타입 등 모든 타입 모두 가능합니다.
type Point = {
x: number;
y: number;
};
// Exactly the same as the earlier example
function printCoord(pt: Point) {
console.log("The coordinate's x value is " + pt.x);
console.log("The coordinate's y value is " + pt.y);
}
printCoord({ x: 100, y: 100 });
interface
interface는 객체 타입만 표현할 수 있습니다. 즉, type 처럼 유니온 타입같은 형식은 표현하지 못합니다.
interface Point {
x: number;
y: number;
}
function printCoord(pt: Point) {
console.log("The coordinate's x value is " + pt.x);
console.log("The coordinate's y value is " + pt.y);
}
printCoord({ x: 100, y: 100 });
type, interface 비교하기
type과 interface의 가장 큰 차이점은 확장 가능성입니다. 인터페이스는 새로운 속성을 추가할 수 있지만 타입은 불가능하다는 점입니다. 이외에도 여러 차이점이 존재하는데요. 각 차이점에 대한 자세한 설명은 다음과 같습니다.
1. 확장 방법
- interface
interface의 경우 아래와 같이 중복 선언을 통한 확장이 가능합니다. 이미 선언한 interface를 다시 한 번 선언하면 속성을 추가할 수 있습니다. 선언을 통한 병합이 이뤄지는 것입니다.
interface Movie {
title: string;
}
interface Movie {
price: number;
}
const movie : Movie = {
title: "interstellar",
price: 10000,
}
또한 interface는 extends 키워드를 통한 확장이 가능합니다.
interface Animal {
name: string;
}
interface Dog extends Animal {
bark: () => void;
}
const dog: Dog = {
name: "happy",
bark: ()=> {console.log("woof woof");}
}
- type
type의 경우 interface와 같은 중복 선언 확장 방법은 사용할 수 없습니다.
type Movie {
title: string;
}
type Movie {
price: number;
}
// ❗️ 에러 발생 : Duplicate identifier 'Movie'.
// type Movie = {
// price: number;
// }
type은 & 키워드를 통한 확장이 가능합니다.
type Animal = {
name: string;
}
type Dog = Animal & {
bark: () => void;
}
const dog: Dog = {
name: "happy",
bark: ()=> {console.log("woof woof");}
}
2. 선언 가능한 타입 종류
- interface
객체 타입만 선언할 수 있습니다.
- type
모든 타입 가능. 객체, 유니온, 교차 타입 등 모든 타입을 선언할 수 있습니다.
type A = string | number | boolean;
type B = {
name: string
}
type C = {
age: number
}
type D = B & C;
const d: D = {
name: "kevin",
age: 42
}
요약
즉 interface는 구조화된 객체 타입을 선언할 때 유용하게 쓰이고, type은 객체보단 유니온, 튜플, 인터섹션 타입 등의 복잡한 타입을 선언할 때 유용하게 쓰입니다.
'백엔드 > Node.js' 카테고리의 다른 글
[TS] 타입스크립트 추론 종류 - 타입 추론(Type Inference) / 리터럴 추론(Literal Inference) (0) | 2025.04.14 |
---|---|
[TS] 타입스크립트 Satisfies 연산자 (4.9 버전부터) (0) | 2025.04.10 |
[TS] 타입 체킹 - 덕 타이핑(Duck Typing, Structural SubTyping)이란? (0) | 2025.04.09 |
[TS] 타입가드(Type Guard)란? (0) | 2025.04.09 |
[TS] 타입 단언(Type Assertion)이란? (0) | 2025.04.09 |