缺少Typescript重复标识符



我正在开发的Angular网页中的TypeScript程序中尝试执行一些if/else语句。这是一个可重复的案例:

export class AppComponent {
x: number = 0;
output: number = 0;
if (this.x < 0.5){
this.output = 1;
}
else if ((this.x >= 0.5) && (this.x < 1.0)){
this.output = 2;
}
else {
this.output = 3;
}
}

在我看来,这与我读过的TypeScript语法教程相匹配,但显然出了问题。

在Visual Studio代码编辑器中,它显示:

  • 重复标识符"(缺少(".ts(2300(
  • 应为标识符。ts(1003(
  • 参数"(缺少("隐式具有"any"类型,但可以根据用法推断出更好的类型。ts(7044(

当我运行代码时,调试控制台会显示:

[WDS] Errors while compiling. Reload prevented.
(webpack)-dev-server/client:162
app.component.ts(10,11): error TS1005: ',' expected.
app.component.ts(10,22): error TS1005: ',' expected.
app.component.ts(10,24): error TS1003: Identifier expected.
app.component.ts(13,3): error TS1068: Unexpected token. A constructor, method, accessor, or property was expected.

您的代码不在函数中。

不确定你想要实现什么。

例如,您可以将代码放入构造函数:

export class AppComponent {
x = 0; // note that the type is inferred therefore the type declaration is not necessary
output = 0;
constructor() {
if (this.x < 0.5){
this.output = 1;
}
else if ((this.x >= 0.5) && (this.x < 1.0)){
this.output = 2;
}
else {
this.output = 3;
}
}
}

您不能只是在类的中间抛出一些语句并期望它工作。您必须创建类方法或将语句添加到类的构造函数或角度生命周期挂钩中。

I。E.

constructor() {
if (this.x < 0.5){
this.output = 1;
}
else if ((this.x >= 0.5) && (this.x < 1.0)){
this.output = 2;
}
else {
this.output = 3;
}
} 

或者myFunct(({…code},然后从某个地方调用this.myFunt((。

最新更新