Andrei Todorut
Andrei Todorut

Reputation: 4526

Private parameters in Typescript

I am learning Angular2 and working with classes in javascript first time.

What does the private parameter and why it couldn't be simply heroService: HeroService ?

constructor(private heroService: HeroService) { }

Upvotes: 74

Views: 24839

Answers (2)

CRice
CRice

Reputation: 32146

Looks like a parameter property. 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:

TypeScript offers special syntax for turning a constructor parameter into a class property with the same name and value. These are called parameter properties and are created by prefixing a constructor argument with one of the visibility modifiers public, private, protected, or readonly. The resulting field gets those modifier(s)

So the following are equivalent:

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

class Foo {
    constructor(private bar: string) {}
}

Upvotes: 113

moohkooh
moohkooh

Reputation: 927

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

Upvotes: 0

Related Questions