JavaScript/TypeScript
Type vs Interface vs Class
창욱씨
2025. 5. 30. 20:35
반응형
Type
Type은 변수 타입 정의에 별칭을 부여하는 것을 의미합니다.
type Color = number | string;
let favoriteColor: Color = "Red";
Object나 Function도 정의하고 재사용할 수 있습니다.
type People = {
name: string;
};
const people: People = {
name: "KIM"
};
type OnError = (id: number, error: string) => boolean;
function downloadFile(id: number, onError: OnError) {
...
}
Type은 변수 타입에 별칭을 부여하고 재사용하는 기능만 제공합니다. 그리고 JavaScript로 변환할 때 어떠한 추가코드도 생성하지 않습니다.
Interface
Interface는 일반적으로 우리가 알고 있는 Interface의 특성을 제공합니다. 위의 Type과 같이 객체의 Type을 제약하는 목적으로도 사용할 수 있습니다.
interface: Person {
name: string;
age: number;
};
interface Professor extends Person {}
class Student implements Person {}
const student: Student = {
name: "KIM",
age: 20
};
Type과 Interface의 차이
type은 모든 타입(객체, primitive)을 선언할 때 사용할 수 있고, interfacesms 객체에 대한 타입을 선언할 때만 사용할 수 있습니다.
interface Person {
name: string;
age: number;
gender: string;
};
// 불가능
interface name extends string { }
type Name = string;
type Age = number;
type Person = [string, number, boolean];
interface는 선언적 확장이 가능하지만 type은 선언적 확장이 불가능합니다.
interface Person {
name: string;
age: number;
}
interface Person { // 선언적 확장
gender: string;
}
const jieun: Person = {
name: 'jieun',
age: 27,
gender: 'female'
}
type Person = {
name: string;
age: number;
}
type Person = { // 위에 type Person이 선언되어 있어서 불가능
gender: string;
}
Class
Class 정보를 바탕으로 새로운 인스턴스를 생성하는 것을 목표로 합니다.
모든 멤버 변수는 초기 값을 가져야 합니다.
class Human {
name: string;
age: number;
constructor() {
this.name = "KIM";
this.age = 20;
}
}
반응형