trungk18 trungk18 - 1 month ago 6
TypeScript Question

Manually and auto assigning constructor parameters in TypeScript

The following code is what I always use to defined a constructor in

TypeScript
so far.

export class DashboardComponent {
private heroService: HeroService;
constructor(heroService: HeroService){
this.heroService = heroService
}
}


But recently when I check the
Angular 2
document, I saw the syntax is shorter and look like

export class DashboardComponent {
constructor(private heroService: HeroService){}
}


And the compiled JavaScript is the same

var DashboardComponent = (function () {
function DashboardComponent(heroService) {
this.heroService = heroService;
}
return DashboardComponent;
}());


Because on the
TypeScript
docs only show the first type so I just want to make sure that two is the same and I am doing correctly with both of those types.

Appreciate If someone can help me to confirm it?

Answer

Yes, the two ways of writing it are effectively the same. You can see the second one being used with public on the official language specification here on GitHub.

So,

class BankAccount {  
    constructor(public balance: number) {}  
}

is the same as

class BankAccount {
    public balance: number
    constructor(balance: number) {
        this.balance = balance;  
    }  
}

Also, a note on the generated JavaScript code : Using private or public won't change the output. Because in pure JavaScript, there's no such thing as a "private" member : You can't prevent an access to a member of your object. The only effect public and private have is telling TypeScript what should and what shouldn't be accessed by other code.

This is also used in an example on Documentation.

Comments