在打字稿中,为什么不能通过调用方法来初始化 class 属性?

In typescript, why isn't it possible to initialize a class property by calling a method?

以下打字稿代码按预期工作,但打字稿在 test2 和 test3 属性上抛出 TS2564 错误。是因为它们是在方法内部初始化的吗?这样的class应该怎么写

我相信它会按预期工作,因为它在 javascript 中有效。会不会是typescript设置错误导致的?

class class1{

    test1:number;//test1 is initialized as expected
    test2:number;//Property 'test2' has no initializer and is not definitely assigned in the constructor.
    test3:number;//Property 'test3' has no initializer and is not definitely assigned in the constructor.

    constructor(){
        //test1 
        this.test1 = 0;

        //test2
        const setTest2To0 = () =>{
            this.test2 = 0;
        };
        setTest2To0();

        //test3
        this.setTest3To0();
    }

    setTest3To0(){
        this.test3 = 0;
    }}

这对我有用:

export class Test {
  name: string;
  age: number;

  constructor() {
      const setNameToHi = (): string => {
          return (this.name = "hi");
      };
      setNameToHi();
      this.setAgeTo3();
  }

  setAgeTo3() {
      this.age = 3;
  }
}

在另一个对象的构造函数中调用它,打印出“hi 3”:

const test: Test = new Test();
console.log(test.name, test.age);

在这种情况下,TypeScript 不跟踪 this 突变。

但是,有一个解决方法。您可以使用 IIFE 模式来声明 test2 属性.

class class1 {

    test1: number;//test1 is initialized as expected
    test2: number;// ok
    test3: number;//Property 'test3' has no initializer and is not definitely assigned in the constructor.

    constructor() {
        //test1 
        this.test1 = 0;

        //test2
        (() => {
            this.test2 = 0;
        })();

        //test3
        this.setTest3To0();
    }

    setTest3To0() {
        this.test3 = 0;
    }
}

您可能已经注意到,TS 能够计算出 test2constructor 中初始化。

请记住,打字稿是关于静态验证的。

So it is impossible to use setTest3To0 to initialize Test3?

是的。你应该使用 test3: number | undefined。或者您可以使用另一种语法:


class class1 {
    static getTest3() {
        return 0
    }

    constructor(public test1 = 0, public test2 = 0, public test3 = class1.getTest3()) { }

}

如果您使用 public 关键字,则无需像以前那样声明所有属性。您可能已经注意到,我在 class 初始化期间使用静态方法设置 test3