Home > Mobile >  Extending a class and making the propeties required
Extending a class and making the propeties required

Time:09-22

There are 2 classes that share part of the code, so I created a Common class.

One of the children classes needs all those properties as required, my idea was to use the Required utility type.

Something like this:

class A extends Common {
  //...
 }

class B extends Required<Common> {
  //...
 }

But I get the error that Required isn't defined. Is there a simple way to achieve what I am looking for (if it is convoluted I will just change the code.)

CodePudding user response:

You can extends Common, and make the properties required using implements:

class Common {
  foo?: string;
  bar?: number;
}

class A extends Common {
  //...
 }

class B extends Common implements Required<Common> {
  constructor(
    public foo: string,
    public bar: number,
  ) {
    super();
  }
 }

Playground

  • Related