class MyClass{
someMethod(): MyClass{
return new MyClass();
}
}
How to reference current class, without explicitly passing the name?
Something like this:
class MyClass{
someMethod(): self{
return new self();
}
}
Obviously that doesn't work, but you get the idea.
TypeScript will not recognize this.constructor as callable. Use Object.getPrototypeOf(this).constructor to get a reference to it instead.
This is the most straightforward way of doing this with strict type safety:
class SelfReference {
/**
* Assign some constructor arguments to the instance for testing.
*/
constructor(private a: number, private b: number) {}
/**
* Create a new instance of `Object.prototypeOf(this).constructor`.
*/
newInstance(...args: ConstructorParameters<typeof SelfReference>) {
const { constructor } = Object.getPrototypeOf(this);
return new constructor(...args);
}
}
const firstReference = new SelfReference(1, 2);
const newReference = firstReference.newInstance(3, 4);
console.log({ firstReference, newReference });
Logs:
[LOG]: {
"firstReference": {
"a": 1,
"b": 2
},
"newReference": {
"a": 3,
"b": 4
}
}
I would not recommend doing this though, it's a pretty ugly anti-pattern.
TypeScript Playground
This can be accomplished by using getPrototypeOf:
Class myclass {
constructor() {}
class(): this {
const ctor = Object.getPrototypeOf(this).constructor;
return new ctor();
}
}
Using the ctor(), we are not calling myclass specifically!
Mozilla - Globa_Objects/Object/getPrototypeOf
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With