【发布时间】:2022-01-04 10:59:37
【问题描述】:
我想创建一个帮助函数isCallback,它返回一个函数是否可调用。
我的类型可以是true,也可以是带有特定参数的回调。在我当前的代码中,我有很多检查,例如 typeof foo === 'function',我想用 isCallback 函数重构这些检查。
我创建了这个辅助函数isCallback:
export const isCallback = (maybeFunction: unknown): boolean =>
typeof maybeFunction === 'function'
我的问题是当我使用 TypeScript 的时候很困惑:
if(isCallback(foo)) {
foo(myArgs) // Error here
}
并抱怨:
This expression is not callable.
Not all constituents of type 'true | ((result: Result) => void)' are callable.
Type 'true' has no call signatures.
如果变量是可调用的并且 TypeScript 也知道它,我如何创建一个返回 true 的函数?
【问题讨论】:
-
(maybeFunction: unknown): boolean->(maybeFunction: unknown): maybeFunction is Function或您想用于该功能的任何接口。但重点是类型保护应该使用is。 -
编译器应该如何知道
boolean的意思是“它是否是一个函数”?你在找type predicates吗? -
也许遵循 VLAZ 的建议,这样的事情会起作用,使用类型保护?
function isCallable(maybeFn: unknown): maybeFn is Function { return typeof maybeFn === 'function'; }
标签: typescript typescript-types