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

TypeScript中如何获取泛型函数指定类型后的参数类型?

解决方案

要获取泛型函数指定泛型参数后的参数类型,你可以通过定义泛型类型别名来实现,直接对泛型函数的类型进行参数化提取:

const fun = <E = any, V = any>(params: { value: V; getValue: (e: E) => V; }) => { /**/ }

type E = { value: string };

// 定义泛型类型别名,提取指定E和V后的参数类型
type FunParams<E, V> = Parameters<typeof fun<E, V>>[0];

// 传入目标泛型参数,得到期望的Params类型
type Params = FunParams<E, string>;

const run = (params: Params) => {
  // 此时params.value类型为string,不再报错
  if (params.value.length > 0) {
    // 参数类型完全匹配,无报错
    fun<E, string>(params);
  }
};

原理说明

typeof fun得到的是泛型函数的构造器类型(即<E, V>(params: ...) => ...),直接用Parameters<typeof fun>时,TypeScript会将未指定的泛型参数解析为默认值(严格模式下会变为unknown),导致类型不匹配。

而通过typeof fun<E, V>先为泛型函数指定具体的类型参数,再用Parameters提取其参数类型,就能得到精确的{ value: string; getValue: (e: E) => string }类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 14:45:24