Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 912
Dan Mandel Avatar asked Feb 25 '26 21:02

Dan Mandel


1 Answers

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;
  }
}

like image 165
Titian Cernicova-Dragomir Avatar answered Feb 27 '26 09:02

Titian Cernicova-Dragomir