Reputation: 12223
In TypeScript is it possible for a class to be a constructor of a function instance? I envision something like:
class SomeThing {
(name: string) {
// do something with name
}
}
let thing = new SomeThing();
thing('John Doe');
Upvotes: 2
Views: 34
Reputation: 221352
It's technically possible (it requires some hacks I'm not going to write here) but you really don't want to do this; here's why.
The new
operator creates a new object (not function) whose __proto__
is the prototype
of the operand. This means you can't possibly have a callable thing returned by the new
operator, unless you explicitly return something else out of the constructor.
But if you return something else out of the constructor, then thing instanceof SomeThing
is going to be false
, and you're not going to be able to use prototype
methods of the class from thing
. So at that point it's not really behaving like a class
at all, and you're better off just having a factory function, which can do whatever it wants.
Upvotes: 4