Search code examples
javascripttypescriptprivate-membersprivate-methods

How to get private methods working in TypeScript?


I have some code that looks roughly like:

class A {
  #hidden = 0;
  method() {
    return this.#hidden;
  }
}

This works fine when I use JS, but when I convert it to TS I get the error Parsing error: Invalid character because of the #. Is there any way I can enable this feature in TS? I am trying to avoid using the private keyword.


Solution

  • Private fields are not yet supported in Typescript. There is a PR on the topic that will probably make it into 3.7 or 3.8 (just an educated guess, not a member of the team, I have no insight into planning).

    In the meantime you could use the old typescript private keyword.

    class A {
      private hidden = 0;
      method() {
        return this.hidden;
      }
    }