You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中使用类型守卫约束函数类型时遇到编译错误的求助

TypeScript中使用类型守卫约束函数类型时遇到编译错误的求助

各位好,我最近在写一个用来判断函数是否无参数的类型守卫,代码是这样的:

function is_zero_args<T, F extends (...args: any[]) => T>(func: F): func is () => T {
  return func.length === 0;
}

我感觉逻辑上是通顺的——通过检查函数的length属性来判断它是不是无参函数,同时用类型守卫把它的类型收窄到() => T。但TypeScript编译时直接报错了,错误信息如下:

A type predicate's type must be assignable to its parameter's type. Type '() => T' is not assignable to type 'F'. '() => T' is assignable to the constraint of type 'F', but 'F' could be instantiated with a different subtype of constraint '(...args: any[]) => T'.

我其实明白F可以被实例化成带不同参数的子类型,但这恰恰是我要做的事情啊——用类型守卫把符合条件的F(也就是无参的那些)收窄成() => T类型。有没有大佬能帮我看看这个问题出在哪,该怎么解决呢?

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 10:38:01