【发布时间】:2018-01-04 05:21:24
【问题描述】:
我明白错误信息:
类型 '() => void' 不可分配给类型 '() => {}'
好吧,它告诉我存在类型转换问题。但是我无法弄清楚为什么编译器认为类型不一样。
代码的背景是我有一个打字稿类,它被赋予了一个函数,然后将其存储为一个成员。我希望能够用一个空的“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;
其他两个语句产生编译错误。
有人知道为什么编译器似乎无法匹配类型吗?
【问题讨论】:
标签: typescript noop