我基本上了解TS2322,但是在这种情况下,我听不懂。
我有一个给定的类定义,如下所示:
export class MyFaultyClass {
functionOrNull: () => void | null;
constructor() {
this.functionOrNull = null; // <- here comes the error TS2322
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题
为什么不能将null分配给已定义的属性?
我的期望
constructor() {
this.functionOrNull = null; // OR
this.functionOrNull = () => {};
}
Run Code Online (Sandbox Code Playgroud)
编辑
这里是一个“工作”的例子:typescriptlang.org/playground 需要启用strictNullChecks。
这是解决方法,然后是说明:
export class MyWorkingClass {
functionOrNull: { () : void } | null;
constructor() {
this.functionOrNull = null; // <- Joy
}
}
Run Code Online (Sandbox Code Playgroud)
因此,当您说() => void | null函数将返回void或null。
当您说它{ () : void } | null;是一个返回的函数时void,或者它为null。
| 归档时间: |
|
| 查看次数: |
1399 次 |
| 最近记录: |