Reputation: 16723
In following component class, if I add let
keyword, the code doesn't compile. Why?
export class HelloComponent {
@Input() name: string;
name2:string;//let name2:string doesn't compile.
constructor(){
}
}
Upvotes: 2
Views: 188
Reputation: 657526
let
and var
are only required/allowed for local variables, not for class fields.
export class HelloComponent {
@Input() name: string;
name2:string;//let name2:string doesn't compile.
constructor(){
var x = 5; // ok
let y = 5; // ok
const z = 5; // ok
}
}
In a class outside a method (or constructor) only variable initialization and method declaration is allowed, therefore let
is redundant and therefore not allowed.
Upvotes: 5
Reputation:
Because you are in a class :
export class HelloComponent
In a class, you declare properties/members that will be accessible like this
let hello = new HelloComponent();
console.log(hello.name2); // In your case, shows "undefined"
This an object property.
For var
and let
, you create block-scoped variables : those are variables that will die once you leave the block of code you're in, such as a function.
Upvotes: 3