[typescript] 추상 클래스와 인터페이스

이번에는 TypeScript에서 추상 클래스와 인터페이스의 차이를 알아보겠습니다. TypeScript는 JavaScript의 상위 집합으로 정적 타입 지정과 다른 언어에도 있는 객체지향적인 특징들을 제공합니다.

인터페이스 (Interfaces)

인터페이스는 TypeScript에서 사용되는 일종의 계약(contract)으로, 객체가 어떤 프로퍼티와 메서드를 가지고 있어야 하는지를 정의합니다. 인터페이스는 클래스가 아니며, 값에 대한 타입을 정의하기 위해 사용됩니다.

예를 들어, 다음과 같이 Car라는 인터페이스를 정의할 수 있습니다.

interface Car {
  make: string;
  model: string;
  start: () => void;
  stop: () => void;
}

그럼 다음과 같이 Car 인터페이스를 구현하는 클래스를 작성할 수 있습니다.

class Toyota implements Car {
  make: string;
  model: string;

  constructor(make: string, model: string) {
    this.make = make;
    this.model = model;
  }

  start() {
    console.log(`${this.make} ${this.model} is starting`);
  }

  stop() {
    console.log(`${this.make} ${this.model} is stopping`);
  }
}

추상 클래스 (Abstract Classes)

추상 클래스는 인스턴스를 만들 수 없는 클래스로, 상속을 통해 자식 클래스에서 구현되어야 하는 메서드를 정의할 수 있습니다. TypeScript에서 추상 클래스는 abstract 키워드를 사용하여 정의됩니다.

abstract class Animal {
  abstract makeSound(): void;
}

위 코드에서 Animal 클래스는 추상 클래스이며, makeSound 메서드는 추상 메서드로 구현이 강제됩니다.

그럼 다음과 같이 Animal 추상 클래스를 상속받는 클래스에서 makeSound 메서드를 구현할 수 있습니다.

class Dog extends Animal {
  makeSound() {
    console.log('Woof! Woof!');
  }
}

결론

인터페이스는 객체의 타입을 정의하는 것이고, 추상 클래스는 객체의 구현을 준비하는 것입니다. 프로젝트에서는 이 두 가지를 조합하여 객체 지향 개발을 할 수 있습니다.

더 자세한 내용은 TypeScript 공식 문서를 참조하세요.