Reputation: 2773
I want to create a function called createInstance
that receives an instance a
and creates a new instance c
that is of the same type as a
. Note that inside of createInstance
I do not know what is the type of a
, I only know it inherits from some class A
. But I want c
to be of type B
, which is the real type of a
. This is what I've got so far:
class A {
constructor(public ref: string) {}
}
class B extends A {
}
const createInstance = (a: A): void => {
const t = a.constructor
const c = new t("c")
console.log(c)
console.log(c instanceof B)
}
const b = new B("b")
createInstance(b)
I've tried it in the typescript playground and it works, I get true
for c instanceof B
. But it shows a warning in the new t("c")
line, that says: "This expression is not constructable. Type 'Function' has no construct signatures."
What is the correct way to do this? Thanks
Upvotes: 1
Views: 880
Reputation: 3501
This actually is still a missing feature in TypeScript, since T.constructor
is not of type T but just a plain function. You can force-cast it:
const t = a.constructor as { new(ref: string): A };
Edit: you can have the constructor already typed (parameters list) using ConstructorParameters
:
const t = a.constructor as { new(...args: ConstructorParameters<typeof A>): A };
See a relative issue on TS repository#4536 and this similar question
Upvotes: 5