如何为函数类型编写打字稿类型保护方法

How to write typescript typeguard method for function type

export const isFunction = (obj: unknown): obj is Function => obj instanceof Function;
export const isString = (obj: unknown): obj is string => Object.prototype.toString.call(obj) === "[object String]";

我想写 isFunction 方法 - 类似于 isString,但是 typescript/eslint 给我一个错误:

Don't use `Function` as a type. The `Function` type accepts any function-like value.
It provides no type safety when calling the function, which can be a common source of bugs.
It also accepts things like class declarations, which will throw at runtime as they will not be called with `new`.
If you are expecting the function to accept certain arguments, you should explicitly define the function shape  @typescript-eslint/ban-types

有什么办法吗?

P.S。答案如下:

export const isFunction = (obj: unknown): obj is (...args: any[]) => any => obj instanceof Function;

JavaScript 有 typeof 运算符,return 是一个指示操作数类型的字符串。对于您的情况,可以这样使用:

export const isFunction = (obj: any) => typeof obj === 'function';
如果 obj 是函数

isFunction 将 return true

嗯,警告很明确...你可以检测到你有一个函数,但你不能推断出很多关于 parameters/arity/return-type 的信息。该信息在 运行 时不可用。它告诉您您不能确定如何调用该函数,或者它是什么returns(在构建时)。

如果您确信这是一个风险,请禁用警告。

// tslint:disable-next-line: ban-types在上面一行。

或者,类型 (...args:any[]) => any 可能是 Function 的一个很好的替代品,但这种类型的函数并不比以前更安全。