1
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

有没有办法做到这一点?

PS这是答案:

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

2 回答 2

3

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

如果这是您有信心的风险,请禁用该警告。

// tslint:disable-next-line: ban-types在上面的线上。

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

于 2021-06-03T12:30:53.467 回答
-2

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

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

isFunctiontrue如果obj是函数,将返回

于 2021-06-03T12:28:50.770 回答