Skip to content

Instantly share code, notes, and snippets.

@vincesp
Last active June 15, 2016 01:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vincesp/36ad316c491f96e648ba709ad298d55a to your computer and use it in GitHub Desktop.
Save vincesp/36ad316c491f96e648ba709ad298d55a to your computer and use it in GitHub Desktop.
Private class members aren't really private in TypeScript. What is the right solution?
function Base() {
var foo = 0;
return {
greet: function () {
++foo;
return "Hello";
},
fly: function() {
return "Flying";
}
}
}
function Special() {
var foo = 0;
var r = new Base();
r.greet = function () {
++foo;
return "Hola";
}
return r;
}
class Base {
private foo = 0;
greet() {
++this.foo;
return "Hello";
}
fly() {
return "Flying";
}
}
class Special extends Base {
private foo = 0;
greet() {
++this.foo;
return "Hola";
}
}
@AbraaoAlves
Copy link

Typescript is an EcmaScript#Next superset and ES not have a specification to private accessors in classes.
Remember TS only add Types and syntax sugar for types, checking this in compile time and remove all types from JS compiled. Like BabelJS, TS does not change ES specification.

If you need to report these members are private to js consumers, maybe you can follow jQuery Widget private member standard.

eg:

class Base {
  private _foo = 0;
  greet() {
    ++this._foo;
    return "Hello";
  }
  private _fly() {
    return "Flying";
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment