Below is the interface and class definition that I have created:
interface Example {
constructor: typeof Example;
}
class Example {
static sample = 'sample';
constructor(data: Partial<Example>) {
Object.assign(this, data);
}
someFunction() {
return this.constructor.sample;
}
prop1: string;
prop2: number;
}
The necessity of the interface is to ensure that this.constructor
has a strong type. However, it poses an issue when trying to pass a plain object into the class constructor:
const instance = new Example({ prop1: 'abcd', prop2: 5678 });
// Argument of type '{ prop1: string; prop2: number; }' is not assignable to parameter of type 'Partial<Example>'.
// Types of property 'constructor' are incompatible.
// Type 'Function' is not assignable to type 'typeof Example'.
// Type 'Function' does not match the signature 'new (data: Partial<Example>): Example'.
I am aware of the error message, but I am unsure of how to resolve it. Is there a way to use Partial<Example>
to allow passing a plain object? Here's a playground link for reference: