Private parameters in Typescript Private parameters in Typescript angular angular

Private parameters in Typescript


Looks like a parameter property (about halfway down the page). Basically, adding an access modifier (public/private/protected/readonly) to a constructor parameter will automatically assign that parameter to a field of the same name.

Specifically, from those docs:

Parameter properties are declared by prefixing a constructor parameter with an accessibility modifier or readonly, or both. Using private for a parameter property declares and initializes a private member; likewise, the same is done for public, protected, and readonly.

So the following are equivalent:

class Foo {    private bar: string;    constructor(bar: string) {        this.bar = bar;    }}class Foo {    constructor(private bar: string) {}}


private will scope this variable for this class (function). public will allow access from outside, if you have the instance of this class. protected is important for properties inside a abstract super class. As i started with Typescript, playground on the TypeScript page (https://www.typescriptlang.org/play/index.html) helped me to understand what really happend. Keep in mind, that TypeScript is sugar for your JavaScript