【问题标题】:Check if variable is callable检查变量是否可调用
【发布时间】: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


【解决方案1】:

正如@jonrsharpe 指出的那样,使用type predicates 有效。

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

【讨论】:

  • 为了更普遍有用(并且更好地反映实际实现检查的内容),它可能应该是(maybeFunction: any) => maybeFunction is Function。这仍然会从true | ((...args: any[]) => void) 缩小到(...args: any[]) => void
猜你喜欢
  • 1970-01-01
  • 2021-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-20
  • 2012-02-05
  • 2014-09-08
相关资源
最近更新 更多