What is the recommended practice in TypeScript for defining class attributes?
In the Angular 2 demo (The Heroes Tour from angular.io), all attributes are declared as public:
export class Hero {
id: number;
name: string;
}
This allows for instantiation in two different ways:
var hero: Hero = new Hero();
hero.id = 0;
hero.name = "hero";
or
var hero2: Hero = {id : 0, name: "hero"};
Is there a preferred convention similar to Java's style, like this example below?
export class Hero {
private id: number;
private name: string;
setId(id: number): Hero {
this.id = id;
return this;
}
setName(name: string): Hero {
this.name = name;
return this;
}
getId(): number {
return this.id;
}
getName(): string {
return this.name;
}
}
Usage (example):
var hero: Hero = new Hero();
hero.setId(0).setName('hero');
var hero2: Hero = new Hero().setId(0).setName('hero');