Making instance via constructor property of another instance (TS2351: This expression is not constructable)

Viewed 720

I need to instantiate some class which I have no access to. What I have is another instance of that class. In other words: the library does not export class, but its instance only, and I want to have another instance. The following code does solve the issue:

const myInstance = new importedInstance.constructor(params);

It works fine as pure javascript, but not as typescript. Typescript throws an error:

TS2351: This expression is not constructable. Type 'Function' has no construct signatures.

Is there any solution for typescript other than any-cast like new (importedInstance as any).constructor(params)?

1 Answers

You can tell TypeScript the constructor has a construct signature by using new () => InstanceType. So in your case it would become something like this:

const myInstance = new (importedInstance.constructor as 
    new(...params: typeof params) => typeof importedInstance)(params);
Related