为什么添加关键字 `let` 或 `var` 会使代码无法编译

Man*_*dha 2 typescript angular

在下面的组件类中,如果我添加let关键字,代码不会编译。为什么?

export class HelloComponent {
  @Input() name: string;
  name2:string;//let name2:string doesn't compile.

  constructor(){

  }
}
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 5

let并且var仅需要/允许用于局部变量,而不用于类字段。

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
  }
}
Run Code Online (Sandbox Code Playgroud)

在方法(或构造函数)之外的类中,只允许变量初始化和方法声明,因此let是多余的,因此是不允许的。