Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading