자바스크립트는 객체지향 언어로 ES6부터 Class
기능이 추가되었다.
타입스크립트는 타입체크와 정적 프로퍼티 등의 추가 기능으로 자바스크립트 클래스를 향상시킨다. 클래스는 자바스크립트로 transpile 될때 transpiled 파일에 보관된다.
클래스는 객체로 프로퍼티와 메소드를 정의할 수 있다.
class FruitStore {
create(data: { name: string; price: number }) {
return { name: data.name, price: data.price }
}
}
const fruitStore = new FruitStore();
const apple = fruitStore.create({
name: 'apple',
price: 1000,
});
console.log(apple); // { name: 'apple', price: 1000 }
new
생성자를 통해 fruitStore 인스턴스를 생성한 후 create 메소드를 사용하였다. 위 속성을 이용하여 타입스크립트에서는 타입체크를 위해 클래스를 사용할 수 있다.
class Fruit {
constructor(public name: string, public price: number) {}
}
class FruitStore {
create(data: Fruit) {
return { name: data.name, price: data.price }
}
}
Fruit 클래스에서 우리는 생성자 인수(constructor)을 통해 name과 price라는 프로퍼티를 정의할 수 있다. Fruit 클래스를 FruitStore의 create 메소드 인수의 타입체크용으로 사용할 수 있다.
FruitStore는 좀 더 선언적이고 읽기 쉽게 만들어졌다. 또한 Fruit의 정의를 export
하면 다른 모든 클래스에서 접근 가능하다.
인터페이스는 타입스크립트 컨텍스트
내에만 존재하는 가상구조이다. 자바스크립트로 transpile 될때 코드에서 인터페이스는 사라진다.
클래스는 프로퍼티 초기화, 메소드 구현을 제공함으로써 팩토리나 싱글톤을 정의할 수 있지만, 인터페이스는 객체의 프로퍼티를 정의하는 단순한 계약구조이다.
interface Fruit {
name: string;
price: number;
}
class FruitStore {
static create(data: Fruit) {
return { name: data.name, price: data.price }
}
}
Fruit는 타입체크 용도로만 사용되기 때문에 클래스던 인터페이스던 코드 전체에 전혀 영향을 미치지 않는다. 다만 Fruit를 인터페이스로 선언하면 인스턴스를 생성할 수 없게 된다.
클래스는 동일한 프로퍼티 및 메소드를 공유하는 객체를 만들 수 있다. 인터페이스는 객체를 설명하는 관련 프로퍼티 및 메소드의 그룹이지만 구현이나 초기화를 제공하지 않는다.
두 객체 모두 타입체크용으로 사용되지만, 인터페이스를 사용하면 코드의 명확성과 가독성이 떨어지게 된다.
class Fruit {
constructor(public name: string, public price: number) {}
}
class FruitStore {
static create(data: Fruit) {
return new Fruit(data.name, data.price);
}
}
const apple = FruitStore.create({name: 'apple', price: 1000});
console.log(apple);
/*
Fruit {
name: 'apple',
price: 1000,
__proto__: { constructor: ƒ Fruit() }
}
*/
interface Fruit {
name: string;
price: number;
}
class FruitStore {
create(data: Fruit) {
return new Fruit(data.name, data.price);
// ReferenceError: Fruit is not defined
}
}