This page looks best with JavaScript enabled

Public and Private Variables in Typescript

 ·   ·  ☕ 2 min read

Are public and private variables really public or private?

Consider the below example -

1
2
3
4
5
6
7
class MathOp {
  public x: number;
  private y: number;
}

const op = new MathOp();
op.x; // no problem

If you try to access the private variable..

1
2
op.y;
// Error: Property 'y' is private and only accessible within class 'MathOp'

What does private even mean?

From our earlier definitions, the behaviour seems ok.

Or, is it?

Just compile the above code block to JS.

1
tsc test1.ts

And, the compiled Javascript file is -

1
2
3
4
5
6
var MathOp = /** @class */ (function() {
  function MathOp() {}
  return MathOp;
})();
var op = new MathOp();
op.x; // no problem

There is no mention of variables x and y in the class since they are just props. These props of the function can be dynamically defined and created.

There is nothing in the compiled Javascript that will have a problem running the script even if something is defined as private.

But, private does prevent successful compilation.

End result: we are pretty much covered with the private variables but be aware of compile and runtime differences in behaviour.

public can be dropped from the statements

You can as well rewrite the Typescript file as -

1
2
3
4
5
6
7
class MathOp {
  x: number;
  private y: number;
}

const op = new MathOp();
op.x; // no problem

Variables and methods are public by default - you can save on your typing a bit by dropping the public keyword altogether.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things