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

问题描述 投票:0回答:3
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

有什么办法可以做到这一点吗?

附注答案如下:

export const isFunction = (obj: unknown): obj is (...args: any[]) => any => obj instanceof Function;
javascript typescript function type-safety narrowing
3个回答
4
投票

嗯,警告很明确......您可以检测到您有一个函数,但您无法推断出太多有关参数/数量/返回类型的信息。该信息在运行时不可用。它告诉您,您无法确定如何调用该函数,或者它返回什么(在构建时)。

如果您确信存在风险,请禁用警告。

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

或者,类型

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


0
投票

你应该使用接口

CallableFunction
,使你的typeguard功能像这样:

export const isFunction = (obj: unknown): obj is CallableFunction => obj instanceof Function;

通过这种方式,函数的类型与构造函数的类型分开(可以使用类型

NewableFunction
来键入)。


-4
投票

JavaScript 有

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

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

isFunction

 是一个函数,
true
将返回
obj

© www.soinside.com 2019 - 2024. All rights reserved.