类型'null'不能分配给类型'()=> void | 空值'

sci*_*per 2 typescript

我基本上了解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。

Fen*_*ton 7

这是解决方法,然后是说明:

export class MyWorkingClass {
    functionOrNull: { () : void } | null;

  constructor() {
    this.functionOrNull = null; // <- Joy
  }
}
Run Code Online (Sandbox Code Playgroud)

因此,当您说() => void | null函数将返回voidnull

当您说它{ () : void } | null;是一个返回的函数时void,或者它为null。

  • `functionOrNull: (() =&gt; void) | null;` 也应该工作 (5认同)