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

TypeScript复用泛型函数参数类型时丢失泛型约束问题

解决TypeScript泛型函数参数类型复用丢失约束的问题

当你用Parameters<typeof example>[0]提取泛型函数的参数类型时,TypeScript会将泛型参数T解析为unknown,导致原有的条件类型约束(T extends number ? number : never)失效,所以example2无法正确校验参数。

下面提供两种可行的解决方式:

方式一:提取泛型参数类型为独立别名

把example的参数类型单独提取成泛型类型别名,让example和example2共同复用这个类型,保留泛型约束:

// 提取泛型参数类型
type ExampleArgs<T> = {a: T, b: T extends number ? number : never};

const example = <T,>(args: ExampleArgs<T>) => {
  console.log(args.a, args.b);
};

const example2 = <T,>(args: ExampleArgs<T>) => {
  console.log(args);
};

example2({a: 12, b: 13}); // 正常通过校验
example2({a: 'foo', b: 13}); // 触发预期的类型警告

方式二:直接复用原函数的泛型类型

让example2直接继承example的泛型函数类型,自动获得相同的参数约束:

const example = <T,>(args: {a: T, b: T extends number ? number : never}) => {
  console.log(args.a, args.b);
};

// 复用example的泛型函数类型
const example2: typeof example = (args) => {
  console.log(args);
};

example2({a: 12, b: 13}); // 正常通过校验
example2({a: 'foo', b: 13}); // 触发预期的类型警告

两种方式都能让example2拥有和example完全一致的参数类型约束,解决类型丢失的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 02:51:04