Skip to content

Please extend polymorphic this support to static methods as wellΒ #61522

Closed
@rp-pedraza

Description

@rp-pedraza

πŸ” Search Terms

static polymorphic this

βœ… Viability Checklist

⭐ 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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions