Home > database >  is it possible to implement part of interface in a class, and the rest in a subclass?
is it possible to implement part of interface in a class, and the rest in a subclass?

Time:10-27

Suppose I have the following structure:

interface ParentInterface {
  foo(): string;
  print(): void;
}

class ParentClass implements ParentInterface {
  print() { console.log(this.foo()); }
}

class ChildClassA extends ParentClass {
  foo() { return "foo-A"; }
}

class ChildClassB extends ParentClass {
  foo() { return "foo-B"; }
}

Of course this isn't valid typescript, because ParentClass doesn't implement ParentInterface's method 'foo()';

Is it possible to structure it in a different way to achieve this result?

CodePudding user response:

Make the parent class abstract

abstract class ParentClass implements ParentInterface {
  print() { console.log(this.foo()); }

  abstract foo(): string
}

Playground

  • Related