我理解了错误信息:
类型“() => void”不能赋值给类型“() => {}”
嗯,有点明白了,它告诉我存在类型转换问题。但是我无法弄清楚为什么编译器认为这些类型不同。
代码的背景是,我有一个 TypeScript 类,该类接收一个函数并将其存储为成员。我想能够使用空的“noop”函数来初始化成员,以便在使用之前不必进行空值检查。
我已经成功将问题缩小到以下示例测试代码:
export class Test {
private _noop: () => {};
constructor(
) {
this._noop = () => { }; //I guess the compiler thinks this is returning in a new empty object using the json syntax
this._noop = this.noop; //I would have thought this shoud definitely work
this._noop = () => undefined; //This does works
}
public noop(): void {
//Nothing to see here...
}
}
构造函数中的三个语句都是为了完成同一个任务:用无操作函数初始化成员。然而,只有最后一个语句起作用:
this._noop = () => undefined;
另外两个语句会产生编译错误。
有人知道为什么编译器似乎无法匹配类型吗?