Interface VS Type
1. interface
interface는 주로 객체의 구조를 정의할 때 사용됩니다. 객체의 속성이나 메서드의 형태를 설명하고자 할 때 interface를 활용합니다. 아래는 interface를 사용한 간단한 예시입니다.
interface Person {
name: string;
age: number;
}
const person: Person = {
name: 'John',
age: 30,
};
2. type
type은 기본적으로 interface와 비슷한 역할을 수행하지만, 좀 더 범용적으로 사용할 수 있습니다. 객체뿐만 아니라 유니온 타입, 튜플 등 다양한 타입을 정의할 수 있습니다. 아래는 type을 사용한 예시입니다.
type Person = {
name: string;
age: number;
};
const person: Person = {
name: 'John',
age: 30,
};
공통점
두 방식 모두 타입을 정의하고 재사용 가능하게끔 만들어줍니다. 또한, 확장성이 있어 새로운 속성을 추가하거나 기존 속성을 재정의할 수 있습니다.
// interface에서의 확장
interface Person {
name: string;
age: number;
}
interface ExtendedPerson extends Person {
email: string;
}
// type에서의 확장
type Person = {
name: string;
age: number;
};
type ExtendedPerson = Person & { email: string };
선택적 속성
interface에서는 속성을 만들 때 ?를 사용하여 선택적으로 정의할 수 있습니다.
interface Person {
name: string;
age?: number; // 선택적 속성
}
type에서도 동일한 방법으로 선택적 속성을 정의할 수 있습니다.
type Person = {
name: string;
age?: number; // 선택적 속성
};
interface를 사용: 대부분의 경우 interface를 사용하는 것이 더 명확하고 읽기 쉽습니다. 특히 객체의 구조를 정의할 때는 interface를 사용하는 것이 일반적
타입 확장이나 유니온, 인터섹션 등의 경우에는 type을 사용: 조금 더 확장성 있는 타입 정의가 필요한 경우에는 type을 사용하는 것이 좋습니다.
1. 유니온 타입
유니온 타입은 여러 타입 중 하나일 수 있는 값을 정의할 때 사용합니다.
type Result = 'success' | 'error';
const handleResult = (result: Result) => {
if (result === 'success') {
console.log('Operation succeeded!');
} else {
console.error('Operation failed!');
}
};
handleResult('success'); // OK
handleResult('warning'); // 에러: 'warning'은 'success' 또는 'error'가 아님
2. 인터섹션 타입
인터섹션 타입은 두 개 이상의 타입을 결합할 때 사용합니다.
type User = {
name: string;
age: number;
};
type Admin = {
isAdmin: boolean;
};
type AdminUser = User & Admin;
const adminUser: AdminUser = {
name: 'John',
age: 30,
isAdmin: true,
};
3. 타입 확장
type을 사용하여 타입을 확장할 수 있습니다.
type Animal = {
name: string;
age: number;
};
type Dog = Animal & {
breed: string;
};
const myDog: Dog = {
name: 'Buddy',
age: 3,
breed: 'Golden Retriever',
};
이와 같이 type을 사용하면 필요에 따라 타입을 유연하게 조합하고 확장할 수 있습니다. 따라서 유니온, 인터섹션, 타입 확장 등의 상황에서는 type이 더 적합하게 사용됩니다.