I am currently facing an issue with a function that takes a constructor as a parameter and creates an instance based on that constructor. When attempting to check the type of the constructor, I encountered an error.
Below are some snippets of code that I have experimented with:
First attempt:
function hello(arg: Function) {
if(arg instanceof typeof MyClass) { // .. constructor(a: number) ..
return new arg(123)
} else if(arg instanceof typeof MyClass2) { // .. constructor(a: string) ..
return new arg('abc')
} else return arg(true)
}
This resulted in the following error:
The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type. ts(2359)
Second attempt:
// ...
if (arg.prototype instanceof Component) {
const hi = new arg(123)
// ...
}
However, this also led to an error:
Cannot use 'new' with an expression whose type lacks a call or construct signature. ts(2351)
My goal is to validate the type of certain constructors like so:
hello(MyClass) // new MyClass(123)
hello(MyClass2) // new MyClass2('abc')