首页 > 解决方案 > 类不继承属性初始化状态

问题描述

我有这种情况,当我继承一个类时,基类中的属性不会被识别为在扩展类中初始化。我不确定这是否是打字稿或 tslint 的问题,我在谷歌上找不到任何东西(可能没有搜索正确的东西)。

(属性) BaseClass.myProperty: IMyProperty | 未定义对象可能是“未定义”.ts(2532)

tsconfig.json

{
  "compilerOptions": {
    "strict": true
  }
}

例子.ts

interface IMyProperty{
  myName: string;
}

class BaseClass {
  readonly myProperty: IMyProperty | undefined;
  constructor(options: IMyProperty){
    this.myProperty = options
  }
}

class ExtendedClass extends BaseClass{
  constructor(options: IMyProperty){
    super(options)
  }

  printMyName(){
    console.log(this.myProperty.myName); // <-- Complains about this
  }
}

const extendedClass = new ExtendedClass({myName: 'John Smith'});
extendedClass.printMyName();

标签: node.jstypescript

解决方案


因为您声明它myProperty可以是未定义的,所以 TypeScript 必须抱怨访问可能未定义的值。这是因为 TS 无法知道您是否没有在代码中的其他位置重新分配值。

const extendedClass = new ExtendedClass({myName: 'John Smith'});
extendedClass.myProperty = undefined
extendedClass.printMyName(); // Would throw a runtime error.

为了解决这个问题,您必须添加一个警戒检查值是否在执行时正确定义。

class ExtendedClass extends BaseClass {
  printMyName() {
    // if (this.myProperty) { ... } would also work.
    if (typeof this.myProperty !== 'undefined') {
      console.log(this.myProperty.myName); // Now it works. TS know it can't be undefined at this point.
    }
  }
}

推荐阅读