type ResolverFn = () => any;
// type Notifications = () => any | number; // works as expected
type Notifications = ResolverFn | number;
// when using the named function, ResolverFn, it fails with error:
// "Cannot invoke an expression whose type lacks a call signature. Type 'Notifications' has no compatible call signatures."
// but it works with the unnamed () => any
type Query = {
notifications: Notifications;
};
const Query: Query = {
notifications() {}
};
const notifications: Notifications = () => {};
notifications();
Query.notifications();
上面的例子非常简单,是从更复杂的例子中推导出来的。实际上,没有一种类型的签名是函数或数字。在这里,它只是用来展示行为上的差异。
还有与此错误相关的其他问题,但我找不到我的具体问题的答案:
为什么命名和未命名函数有不同的行为?这是预期的行为吗?为什么?有解决方法吗?假设问题是来自我们无法修改的外部程序包,即使它可能是错误的。
内联函数类型“起作用”的原因是因为它没有按照您认为的那样做:它描述了any | number
由于优先规则而返回的函数。注意区别:
// A function returning either any or number
type A = () => any | number;
// Either a function returning any — or a number
type B = (() => any) | number;
否则它不起作用的原因是因为不清楚notifications
函数类型,它也可能是数字,并且数字不可调用。
如@Przemyslaw Pietrzak的答案所指出的,请使用类型防护来缩小类型:
if (typeof notifications === "function") {
notifications();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句