检查变量是否可调用

Check if variable is callable

我想创建一个辅助函数 isCallback 来确定 returns 函数是否可调用。

我有一个类型可以是 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 也知道它,我如何创建一个 returns true 的函数?

因为@jonrsharpe pointed out, using type predicates有效。

export const isCallback = (
  maybeFunction: true | ((...args: any[]) => void),
): maybeFunction is (...args: any[]) => void =>
  typeof maybeFunction === 'function'