【问题标题】:Typescript duplicate identifier missing打字稿重复标识符丢失
【发布时间】:2020-08-04 15:05:06
【问题描述】:

我正在尝试在我正在开发的 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 Code 编辑器中,它显示:

  • 重复标识符“(缺失)”.ts(2300)
  • 预期标识符.ts(1003)
  • 参数 '(Missing)' 隐式具有 'any' 类型,但可以从 usage.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.

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    您的代码不在函数中。

    不确定您要达到的目标。

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

    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;
        }
      }
    }
    

    【讨论】:

    • 谢谢!这是有道理的,它解决了我的问题。我没有意识到我可以在类内部但在函数外部声明变量,但不能执行代码。
    【解决方案2】:

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

    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.myFunct()。

    【讨论】:

      猜你喜欢
      • 2016-09-20
      • 2017-08-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-10
      • 1970-01-01
      • 1970-01-01
      • 2015-09-28
      • 2020-04-22
      相关资源
      最近更新 更多