Node.js 类不继承属性初始化状态
在这种情况下,当我继承一个类时,基类中的属性不会被识别为在扩展类中初始化。我不确定这是否是typescript或tslint的问题,我在google上找不到任何东西(可能没有搜索正确的东西) (property)BaseClass.myProperty:IMyProperty |未定义的对象为 可能是“未定义”。ts(2532) tsconfig.jsonNode.js 类不继承属性初始化状态,node.js,typescript,Node.js,Typescript,在这种情况下,当我继承一个类时,基类中的属性不会被识别为在扩展类中初始化。我不确定这是否是typescript或tslint的问题,我在google上找不到任何东西(可能没有搜索正确的东西) (property)BaseClass.myProperty:IMyProperty |未定义的对象为 可能是“未定义”。ts(2532) tsconfig.json { "compilerOptions": { "strict": true } } 示例.ts interface IMy
{
"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();
接口IMyProperty{
我的名字:字符串;
}
类基类{
只读myProperty:IMyProperty |未定义;
构造函数(选项:IMyProperty){
this.myProperty=options
}
}
类ExtendedClass扩展基类{
构造函数(选项:IMyProperty){
超级(选项)
}
printMyName(){
console.log(this.myProperty.myName);//因为您声明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.
}
}
}
在console.log()
语句中,您试图记录myName,但正如编译器错误所述,this.myProperty
可能未定义。因此,不允许使用此语句,因为您无法访问未定义的对象(this.myProperty)的属性(myName)
为什么myProperty
是未定义的呢?你能删除基类中的|undefined
吗?这会解决你的问题。我想这种方法解决了这个问题,但看起来还是不太优雅
interface IMyProperty {
myName: string;
}
class BaseClass {
readonly myProperty: IMyProperty | undefined;
constructor(options: IMyProperty) {
this.myProperty = options
}
}
class ExtendedClass extends BaseClass {
readonly myProperty: IMyProperty;
constructor(options: IMyProperty) {
super(options);
this.myProperty = options;
}
printMyName() {
console.log(this.myProperty.myName);
}
}
const extendedClass = new ExtendedClass({ myName: 'John Smith' });
extendedClass.printMyName();
很抱歉,我忘了提到我设置为只读。我真的不想添加防护,因为该属性将被大量使用。此外,如果使用基类构造函数,它也不会抱怨。readonly
不能保证运行时代码不会更改任何内容,因此TS仍然正确。请尝试extendedClass['my'+'property']=undefined
并查看它是否有效。如果确实不想保护代码,可以使用!
确保属性存在:this.myProperty!.myName
。它正在从类外部初始化。我希望BaseClass.myProperty不可定义,但ExtendedClass的所有实例都应希望myProperty初始化。然后正如Mateusz所说,您应该使用非空断言运算符!
,或者断言myProperty
在ExtendedClass
构造函数或printMyName()中未定义
不幸的是,即使我在扩展类中声明它,我仍然必须在扩展类中显式地分配它。即使基类已经这样做了。