Reputation: 33
I'm trying to write a function that will create a instance from a class and do some operations on some of its members
function presetInstance<T>(baseClass: any, members: Array<keyof T>) {
const instance: T = new baseClass();
// ...
}
It works but it leads to code that feels like it should improved:
const instance = presetInstance<BaseClass>(BaseClass, ['foo', 'bar']);
Is there a way to only write this ?
const instance = presetInstance(BaseClass, ['foo', 'bar']);
Upvotes: 2
Views: 43
Reputation: 9907
Yes, you can use a type such as this:
interface IConstructor<T> {
new(): T;
}
Now, change the function signature to:
presetInstance<T>(baseClass: IConstructor<T>, members: Array<keyof T>)
This way, typescript can infer that baseClass
creates an instance of T
when constructed with new
.
Upvotes: 2