Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
6 tasks done
rp-pedraza opened this issue Apr 2, 2025 · 3 comments
Closed
6 tasks done

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

rp-pedraza opened this issue Apr 2, 2025 · 3 comments

Comments

@rp-pedraza
Copy link

rp-pedraza commented Apr 2, 2025

πŸ” 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.

@rp-pedraza
Copy link
Author

And it would be nice to be able to specify this in local castings as well:

    return (this as { __singleton_instance?: this }).__singleton_instance ?? new this()

@MartinJohns
Copy link
Contributor

Duplicate of #5863. Used search terms: this static in:title

@rp-pedraza
Copy link
Author

Closing as duplicate

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants