【问题标题】:Typescript setting class variable from contructor via method callTypescript将类变量从构造函数设置为方法调用
【发布时间】:2020-11-20 00:03:58
【问题描述】:

打字稿可以推断从构造函数调用的方法设置实例变量。

Typescript 编译器报错

" 属性“变量”没有初始值设定项,也没有在构造函数中明确分配。 "

下面的代码:

class A {

  private variable: string;
  private constructor() {
        this.setVariable("default");
    }

  public setVariable(value: string){
       this.value = value;
  }

}

这迫使我使用 ts-ignore:

// ts-ignore 
  private variable: string;

【问题讨论】:

  • private variable: string = '';private variable!: string;
  • 不,因为不能保证class A 的消费者会调用​​setVariable。没有强制A 的客户致电setVariable。因此,这里无法实现可靠的推理。

标签: typescript


【解决方案1】:

必须在构造函数中赋值,即

class A {
  private variable: string; // No error
  private constructor() {
    this.variable = 'default'; // Cause assigned
  }

  public setVariable(value: string){
       this.variable = value;
  }
}

调用初始化它的方法不算数。

【讨论】:

    猜你喜欢
    • 2016-05-31
    • 2016-03-10
    • 1970-01-01
    • 2021-01-19
    • 1970-01-01
    • 1970-01-01
    • 2017-07-16
    • 2019-02-22
    • 2013-08-10
    相关资源
    最近更新 更多