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