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

使用type-fest的GreaterThan作为函数参数类型遇TypeScript错误求助

问题:type-fest GreaterThan类型约束函数参数触发TypeScript错误

代码示例

import type {GreaterThan} from 'type-fest'

function printNumberOfBooks <N extends number> (numberOfBooks: GreaterThan<N, 0>): void {
    console.log(numberOfBooks)
}

错误信息

Argument of type 'number' is not assignable to parameter of type 'never'

调用printNumberOfBooks(2)时触发上述错误。


原因分析

GreaterThan<N, 0>的返回值是布尔类型(true/false),并非用来直接定义参数的数值类型。你现在把它当作参数的类型注解,TypeScript无法推断出符合GreaterThan<N,0>的具体N类型,最终解析为never,导致类型不匹配。


解决方案

要实现“参数必须是大于0的数字”的约束,需要用GreaterThan来约束泛型N的范围,而非直接作为参数类型。以下是两种可行写法:

写法1:条件类型约束参数类型

import type { GreaterThan } from 'type-fest';

function printNumberOfBooks<N extends number>(
  numberOfBooks: GreaterThan<N, 0> extends true ? N : never
): void {
  console.log(numberOfBooks);
}

写法2:通过返回值条件类型约束

import type { GreaterThan } from 'type-fest';

function printNumberOfBooks<N extends number>(
  numberOfBooks: N
): GreaterThan<N, 0> extends true ? void : never {
  console.log(numberOfBooks);
}

验证效果

  • printNumberOfBooks(2):类型检查通过,正常执行
  • printNumberOfBooks(0)/printNumberOfBooks(-1):触发类型错误,符合预期

内容的提问来源于stack exchange,提问作者cyspex

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 22:42:03