node.js - 类不继承属性初始化状态
问题描述
我有这种情况,当我继承一个类时,基类中的属性不会被识别为在扩展类中初始化。我不确定这是否是打字稿或 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();
解决方案
因为您声明它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.
}
}
}
推荐阅读
- c++ - 如何设置 libgps 调试级别?
- excel - 如何创建宏以在我当前选择的列上执行 TextToColumn,目标必须是相同的列
- javascript - 如何在重新定向时获取用户输入的 Chrome 新标签的 URL
- c++ - 大小的时间复杂度是多少?
- hasura - hasura_session 不带参数的调用
- ios - 根据滚动百分比逐渐更改 TableViewCell 图层背景颜色
- javascript - 上传大文件在 Windows 上不起作用?
- pca - 如何将 PCA 与具有相同单位的值的数据一起使用
- python - Excel到文本文件数组dtype之间不匹配('
目前我是:
- 从 Excel 工作表中提取列
- 将它们保存为矩阵
我想将新矩阵保存在文本文件中
import pandas as pd import os, sys import pand
- kubernetes - sed 将第二个值归零