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

Include an interface into a class in a .d.ts file

I have a JavaScript class that extends the instance with constructor options:

class C {
  constructor(options) {
    Object.assign(this, options)
  }
}

That means that the class instance is going to have all of the properties of the options object.

I’m looking for a way to write a .d.ts definition for that class without duplicating interface properties:

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

interface Options {
  foo: number;
  bar: string;
}

class C {
  foo: number;
  bar: string;

  constructor(options: Options);
}

Is there a way to include all of the Options interface properties? Tried the following, but that’s not valid TypeScript:

class C {
  ...Options;

  constructor(options: Options);
}

>Solution :

In TypeScript, you can achieve this by using the intersection type (&). You can create an interface that represents the class properties and then intersect it with the Options interface. Here’s how you can do it:

interface Options {
  foo: number;
  bar: string;
}

interface C extends Options {}

class C {
  constructor(options: Options) {
    Object.assign(this, options);
  }
}

// Example usage
const instance = new C({ foo: 42, bar: "hello" });
console.log(instance.foo); // 42
console.log(instance.bar); // "hello"

In this example, the C class extends the Options interface, which means it inherits all the properties of the Options interface. The constructor function then enforces that the options parameter must conform to the Options interface.

This way, you avoid duplicating the property definitions in both the Options interface and the C class. If you add or remove properties from the Options interface, the C class will automatically reflect those changes.

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