TypeScript 意外标记,需要构造函数、方法、访问器或 属性

TypeScript Unexpected token, A constructor, method, accessor or property was expected

只是尝试使用 typescript 在 class 中编写一个函数。

class Test 
{
    function add(x: number, y: number): number {
        return x + y;
    }
}

这会导致以下错误:

TypeScript Unexpected token, A constructor, method, accessor or property was expected.

我复制了示例:https://www.typescriptlang.org/docs/handbook/functions.html

我错过了什么吗?我很困惑!

您不应在 Typescript class 定义中使用 function 关键字。试试这个:

class Test { 
    add(x: number, y: number): number {
        return x + y;
    }
}

TypeScript 不允许 function 声明为 class 成员;它的语法略有不同...

class Test 
{
    // This will bind the add method to Test.prototype
    add(x: number, y: number): number 
    {
        return x + y;
    }

    // This will create a closure based method within the Test class
    add2 = (x: number, y: number) => {
        return x + y;
    }
}

当您尝试在生命周期挂钩之外访问 属性 时,也会抛出相同的错误。您需要在生命周期挂钩或构造函数中访问它们,例如:

class Test {

  x: number;
  y: number;

  add(x: number, y: number): number {
    this.x = x;
    this.y = y;
    return this.x + this.y;
  }
}

...
export class Component implements OnInit {

  test: Test = new Test();
  test.x = 0; // NOK, will throw: Unexpected token, A constructor... error

  constructor() { 
    test.x = 0; // OK
  }

  ngOnInit(): void {
    test.x = 0; // OK
  }
}