Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/436.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何为函数类型编写typescript typeguard方法_Javascript_Typescript_Function_Type Safety_Narrowing - Fatal编程技术网

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

Javascript 如何为函数类型编写typescript typeguard方法,javascript,typescript,function,type-safety,narrowing,Javascript,Typescript,Function,Type Safety,Narrowing,我想编写isFunction方法-类似于isString,但typescript/eslint给了我一个错误: export const isFunction = (obj: unknown): obj is Function => obj instanceof Function; export const isString = (obj: unknown): obj is string => Object.prototype.toString.call(obj) === "

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

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]";
有没有办法做到这一点

p.S.答案如下:

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

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

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

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

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

如果您对风险有信心,请禁用警告

//tslint:disable next line:ban type
上一行


或者,键入
(…args:any[])=>any
可能是
函数的好替代,但这种类型的函数的类型安全性并不比以前高。

这里的想法是编写一个类型保护。这个答案完全没有抓住要点。谢谢你的回答@rtarasen,但我们在这里谈论的是typescripttypes@AuthorProxy尽管建议使用
typeofobj==='function'
是测试JS类型的一种更为惯用的方法。
export const isFunction = (obj: any) => typeof obj === 'function';