【发布时间】:2020-05-14 15:18:41
【问题描述】:
这个sn-p
function problem<T>(callback: T | (() => T)) : T {
return typeof callback === 'function' ? callback() : callback;
}
产生错误
This expression is not callable.
Not all constituents of type '(() => T) | (T & Function)' are callable.
Type 'T & Function' has no call signatures. ts(2349)
我花了一段时间才明白Function 本身确实没有多大意义,因为我需要的是一个无参数函数。
在像T = number 这样的特殊情况下,我可以简单地切换到测试typeof callback === 'number' 并完成。但是,我需要一个通用的解决方案。
我愿意
- 要么限制
T,使其不包含函数,这(如我所愿)解决了问题。 - 或对无参数函数进行运行时测试
我也对替代方案持开放态度(我的主要目的是了解细节)。
有哪些可能性?
问题说明
function myfun(s: string) {return s;} 和电话
problem(myfun);
类型T = (s: string) => string 被正确推断。应该没有像myfun()这样的回调调用;相反,应该返回myfun。但是,typeof callback === 'function' 成立时出错了。
更新
假设 检查 callback instanceof Function 与 AFAIK 完全相同,我错了。
这是不同的,正如playground from the answer 所示。但是,添加
const myfun = (s: string) => s;
console.log(problem(myfun));
说出来
Argument of type '(s: string) => string' is not assignable to parameter of type 'string | (() => string)'.
Type '(s: string) => string' is not assignable to type '() => string'.ts(2345)
doAfter.ts(57, 21): Did you mean to call this expression?
这听起来像这行的错误
console.log(problem<(s: string) => string>(myfun));
编译并且没有类型歧义。但是,它不起作用,返回的是 undefined 而不是 myfun 本身。
潜在的重复
链接问题的答案也不能解决我的问题:
- 普通的
correct(myfun);无法编译。 - 有效
correct<(s: string) => string>(myfun)返回未定义。
我的第二个问题“(如何)对无参数函数进行运行时测试”也没有出现在潜在的重复项中。
【问题讨论】:
-
如果您对运行时的这种行为感到满意,您可以使用type predicate 向编译器解释:typescriptlang.org/play/#code/…
-
改用
callback instanceof Function ? callback() : callback怎么样? -
@jonrsharpe 这不是问题所在:Typescript 确实 理解
callback是一个函数。但是,它说它缺少调用签名,这是正确的:请参阅我的编辑。 -
@CRice 我敢打赌,没有任何变化。
-
这能回答你的问题吗? Typescript type T or function () => T usage
标签: typescript callback overloading