-
[TS] type과 interface의 차이개발공부/TypeScript 2025. 2. 28. 10:36
TypeScript에서 타입을 정의할 때 type과 interface 두 가지 방법이 있습니다.
겉보기에는 비슷해 보이지만, 몇 가지 중요한 차이점이 존재합니다.
이번 글에서는 type과 interface의 차이점과 각각의 적절한 사용법을 설명하겠습니다.
목차type과 interface의 개본 개념
type
- 타입 별칭(Type Alias)을 정의할 때 사용
- 간단한 원시 타입부터 복잡한 객체 타입까지 다양하게 활용 가능
interface
- 객체의 구조를 정의하는 데 사용, 주로 클래스와 함께 사용
- 하지만 함수 타입과 함께 사용 가능
type과 interface의 차이점
확장 방식
type은 &(Intersection) 연산자를 사용해 확장 가능
// type 확장 type Person = { name: string; }; type Employee = Person & { company: string; };
interface는 extends 키워드를 사용해 확장 가능
// interface 확장 interface Person { name: string; } interface Employee extends Person { company: string; }
선언 병합 가능 여부
type은 같은 이름으로 선언할 경우 오류 발생
// type은 병합되지 않음 (에러 발생) type User = { email: string; }; type User = { phone?: string; }; // 오류: 동일한 타입 별칭을 다시 선언할 수 없음
interface는 동일한 이름으로 여러 번 선언하면 자동으로 병합
// interface 병합 interface User { email: string; } interface User { phone?: string; } const user: User = { id: 1, name: "John", age: 30, email: "john@example.com", phone: "123-456-7890", };
사용 가능 범위
type은 유니온(|), 인터섹션(&), 튜플, 맵핑된 타입 등 더 다양한 기능을 제공
// type은 유니온 타입을 정의할 수 있음 type Status = "success" | "error" | "loading"; // type은 튜플을 정의할 수 있음 type RGB = [number, number, number];
interface는 객체 구조를 정의하는 데 주로 사용
어떤 경우에 무엇을 사용할까?
- 객체 타입을 정의할 때 → interface 권장 (확장이 용이하고 가독성이 좋음)
- 유니온 타입이나 튜플이 필요할 때 → type 사용
- 함수 타입을 정의할 때 → type과 interface 둘 다 가능하지만 type이 더 간결함
- 외부 라이브러리 타입 확장 시 → interface 사용 (선언 병합 기능 활용 가능)
결론
interface와 type은 각각의 장점이 있으며, 상황에 따라 적절한 것을 선택하는 것이 중요합니다.
일반적으로 객체 타입을 정의할 때는 interface를, 유니온 타입이나 튜플을 사용할 때는 type을 선택하는 것이 좋습니다.
728x90