자바스크립트 클래스에서 abstract 클래스와 인터페이스를 구현할 수 있나요?

그러나 abstract 클래스와 인터페이스의 개념을 구현하기 위해 일부 패턴과 기법을 사용할 수 있습니다. 추상 클래스는 일반 클래스와 마찬가지로 정의할 수 있지만, 인스턴스화할 수 없으며 하위 클래스에서 상속받아 구체화해야 합니다. 인터페이스는 메서드와 속성의 일련의 규칙을 정의하는 역할을 합니다.

아래는 자바스크립트에서 추상 클래스와 인터페이스를 구현하는 예시입니다.

// 추상 클래스
class AbstractClass {
  constructor() {
    if (new.target === AbstractClass) {
      throw new Error('Cannot instantiate abstract class');
    }
  }

  abstractMethod() {
    throw new Error('Abstract method must be implemented');
  }
}

// 하위 클래스에서 상속받아 추상 메서드를 구현
class ConcreteClass extends AbstractClass {
  abstractMethod() {
    console.log('Abstract method implemented');
  }
}

const instance = new ConcreteClass();
instance.abstractMethod(); // 출력: "Abstract method implemented"

// 인터페이스
const MyInterface = {
  abstractMethod() {
    throw new Error('Abstract method must be implemented');
  }
};

// 인터페이스를 구현하는 클래스
class MyClass {
  abstractMethod() {
    console.log('Abstract method implemented');
  }
}

const instance = new MyClass();
instance.abstractMethod(); // 출력: "Abstract method implemented"

하지만 이러한 방식은 공식적인 기능이 아니므로 주의해야 합니다. 자바스크립트의 동적성과 유연성을 이용하여 추상 클래스와 인터페이스와 같은 구조를 모방할 수 있지만, 이는 개발자의 역할이 자동화되지 않고 복잡해질 수 있습니다.

더 나은 대안은 TypeScript와 같은 정적 타입 검사를 지원하는 언어를 사용하는 것입니다. TypeScript는 추상 클래스와 인터페이스를 공식적으로 지원하며 개발자가 이를 더 쉽게 구현하고 사용할 수 있도록 도와줍니다.

참고 자료: