Closed
Description
π Search Terms
static polymorphic this
β Viability Checklist
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
- This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
β Suggestion
Basically allow 'this' return type to be applied to static class methods as well.
π Motivating Example
class Singleton {
constructor() {
if (this.constructor.name === 'Singleton') {
throw new Error("Can't instantiate the Singleton class directly")
}
const subclass = this.constructor as { __singleton_instance?: object }
if (subclass.__singleton_instance) {
throw new Error("Class can only be instantiated once")
}
subclass.__singleton_instance = this
}
public static get instance(): this {
return (this as { __singleton_instance?: object }).__singleton_instance ?? new this()
}
}
class SomeObject extends Singleton {} // No wrapper "get instance" method that explicitly returns SomeObject needed
π» Use Cases
As mentioned above.
Metadata
Metadata
Assignees
Labels
No labels