Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) { }
like image 786
Andrei Todorut Avatar asked Feb 01 '18 20:02

Andrei Todorut


People also ask

What is private parameter?

Private Parameters are used internally, mainly to share a parameter value across multiple transformers. For example, multiple SchemaMappers may reference a single parameter for its schema mapping table dataset. You can also create parameters for username/password fields in commonly accessed database tables.

What does private in TypeScript mean?

TypeScript Private PropertiesA private property of method can only be accessed or called from the class instance itself.

How do I access private properties in TypeScript?

In TypeScript there are two ways to do this. The first option is to cast the object to any . The problem with this option is that you loose type safety and intellisense autocompletion. The second option is the intentional escape hatch.

What is the difference between private and protected variables in TypeScript?

Private methods/members are accessible only from inside the class. Protected methods/members are accessible from inside the class and extending class as well.


1 Answers

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) {} } 
like image 127
CRice Avatar answered Oct 06 '22 13:10

CRice