如何为函数类型编写 typescript typeguard 方法

问题描述

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;

解决方法

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

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

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

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

,

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

export const isFunction = (obj: any) => typeof obj === 'function';

isFunction 将返回 true 如果 obj 是一个函数