If I have two variable names A and b, while A is a class constructor and b is a function, how do I write a function that takes the name as parameter and distinguishes whether it is a class constructor or not?
Or to put it in another way, how do I know if I have to call the function with the new operator or not?
class A{
constructor(){
}
}
function b(){
}
isClass(arg:(new ()=>A) | Function):boolean{
// some code that returns true if arg is a class
}
isClass(b) // false
isClass(A) // true
There is one solution I came up with:
arg.toString().startsWith("class")
This works because arg.toString() returns the definition of arg, in this example something like class A{constructor(){}} for A and function b(){} for b. My solution works but I can imagine there being something neater than that.
Using the typeof operator returns "function" for both A and b, and arg.prototype is only undefined if b is an arrow function.