typescript 类型 '() => void' 不可分配给类型 '() => {}'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45368407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Type '() => void' is not assignable to type '() => {}'
提问by Tom Maher
I understand the error message:
我理解错误信息:
Type '() => void' is not assignable to type '() => {}'
类型 '() => void' 不可分配给类型 '() => {}'
Well sort of, it is telling me there is a type casting issue. However I can't work out why the compiler thinks the types are not the same.
好吧,它告诉我存在类型转换问题。但是我无法弄清楚为什么编译器认为类型不一样。
The back ground to the code is that I have a typescript class that is given a function and then stores it as a member. I want to be able to initialise the member with an empty 'noop' function so that it don't have to null check it before use.
代码的背景是我有一个 typescript 类,它被赋予一个函数,然后将它存储为一个成员。我希望能够使用空的“noop”函数初始化成员,这样它就不必在使用前对其进行空检查。
I have managed to reduce problem down to the following example test code:
我设法将问题减少到以下示例测试代码:
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...
}
}
The three statements in the constructor are all intended to do the same job: initialise the member with a no operation function. However only the last statement works:
构造函数中的三个语句都旨在完成相同的工作:使用无操作函数初始化成员。但是只有最后一条语句有效:
this._noop = () => undefined;
The other two statements produce the compile error.
其他两个语句产生编译错误。
Does any one know why the compiler can't seem to match the types?
有谁知道为什么编译器似乎无法匹配类型?
采纳答案by Saravana
In your definition private _noop: () => {};
_noop
is typed as a function returning an object.
在您的定义中private _noop: () => {};
_noop
被键入为返回对象的函数。
When you assign it as this._noop = () => { };
the function you are trying to assign to _noop
is of type () => void
.
当您将其分配为this._noop = () => { };
您尝试分配的函数时_noop
,类型为() => void
。
If you wanted _noop
to be function returning nothing then type it as:
如果您想_noop
成为不返回任何内容的函数,请键入:
private _noop: () => void;
回答by Val
The below definition means, _noop is a function must return an object (including undefined and null).
下面的定义意味着,_noop 是一个函数必须返回一个对象(包括 undefined 和 null)。
private _noop: () => {};
it's equal to:
它等于:
private _noop: () => Object;
you can make all three statements work with:
您可以使所有三个语句都适用于:
private _noop: () => any;
or the first statement will work with both of these:
或者第一个语句将适用于这两个:
this._noop = () => ({});
this._noop = () => { return {} };