Extending a class and making the propeties required

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.)

>Solution :

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

Leave a Reply