CleanCrispCode CleanCrispCode - 4 months ago 14
TypeScript Question

Understanding "public" / "private" in typescript class

In the below type script code , irrespective of whether name is "public" or
"private" , java script code that is generated is same.

So my question is, how to decide when the constructor parameter should be
public or private ?

// typescript code
class Animal {
constructor( public name: string) {
}

}

// generated JS code
var Animal = (function () {
function Animal(name) {
this.name = name;
}
return Animal;
}());

Answer

java script code that is generated is same

They produce the same JavaScript but don't have the same semantics as far as the type is concerned.

The private member can only be accessed from inside the class whereas public can be excessed externally.

More

The differences are covered here : https://basarat.gitbooks.io/typescript/content/docs/classes.html#access-modifiers

Another example

let foo = 123;

will generate the same ES5 as

const foo = 123; 

However in the first case let foo = 123;foo = 456 will compile fine but const foo = 123; foo = 456 will result in a compile time error.