TypeScript에서 Interface와 Type의 주요 차이점

KUKJIN LEE • 1주 전 작성
TypeScript에서는 데이터를 정의할 때 주로 interface
와 type
을 사용합니다. 두 방식은 비슷해 보이지만, 차이점이 있습니다.
1. 확장성 (Declaration Merging)
-
Interface는 선언 병합(Declaration Merging)이 가능합니다.
interface User {
name: string;
}
interface User {
age: number;
}
// 결과적으로 User는 { name: string; age: number; } 형태가 됩니다.
Type은 선언 병합이 불가능합니다.
type User = {
name: string;
};
type User = { // 오류 발생: Duplicate identifier 'User'
age: number;
};
결론: Interface는 확장성이 뛰어나 여러 파일이나 모듈에서 나눠 정의하는 경우 유용합니다.
2. 유니온 및 인터섹션 타입 활용
-
Type은 유니온(Union) 및 인터섹션(Intersection) 타입을 쉽게 만들 수 있습니다.
-
Interface는 직접 유니온 타입을 정의할 수 없습니다.
type Status = "pending" | "completed" | "failed";
type NumberOrString = number | string;
interface Status = "pending" | "completed" | "failed"; // 오류 발생
결론: 유니온, 인터섹션 같은 복잡한 타입 조합은 Type을 활용하는 것이 더 효과적입니다.
3. 기본적인 사용 사례
-
Interface는 주로 객체 형태의 데이터를 정의할 때 사용합니다.
-
Type은 유니온, 인터섹션, 기본 타입 별칭을 정의하는데 사용합니다.
interface User {
name: string;
age: number;
}
type UserRole = "admin" | "user" | "guest";
type Point = {
x: number;
y: number;
};
4. 성능 차이
성능상 큰 차이는 없지만, 일반적으로 Interface가 TypeScript의 타입 체킹에서 더 나은 성능을 보일 수 있습니다. 그러나 이는 미미한 수준이기 때문에 결정적인 요소는 아닙니니다.