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

如何获取依赖其他参数类型的泛型函数参数类型?

获取依赖于第一个参数的库函数第二个参数类型

问题场景

存在无法修改的库函数,其第二个参数的类型由第一个参数的类型决定。以示例中的libraryFunctionThatWeCantChange为例:

const libraryFunctionThatWeCantChange = <
  T extends string,
  Extra1 extends "A" | "B",
  Extra2 extends Partial<{ name: string, age: number }>
>(
  a: T,
  b: { label: T, type: Extra1, person: Extra2 }
) => {
  return ""
}

当传入第一个参数"firstParameter"后,第二个参数的类型应为:

{
  label: "firstParameter";
  type: "A" | "B";
  person: Partial<{ name: string; age: number; }>;
}

需要将这个类型导出为变量使用,但直接手动写对象无类型提示,用Parameters提取类型时因泛型参数不全而失效。

解决方案

方法一:显式指定泛型默认参数提取类型

通过给库函数的剩余泛型参数指定默认值,直接提取第二个参数的类型:

// 提取第一个参数为T时,第二个参数的类型
type LibrarySecondParam<T extends string> = Parameters<
  typeof libraryFunctionThatWeCantChange<T, "A" | "B", Partial<{ name: string; age: number }>>
>[1];

// 使用类型定义变量,获得完整类型提示
const filler: LibrarySecondParam<"firstParameter"> = {
  label: "firstParameter",
  type: "A",
  person: { name: "Bob" }
};

libraryFunctionThatWeCantChange("firstParameter", filler);

方法二:用条件类型推断封装通用工具

创建通用工具类型提取函数的第二个参数,再结合指定泛型参数使用:

// 通用工具:提取函数的第二个参数类型
type ExtractSecondArg<Func> = Func extends (a: any, b: infer B) => any ? B : never;

// 针对目标库函数,指定第一个参数类型及剩余泛型的默认值
type TargetSecondParam<T extends string> = ExtractSecondArg<
  typeof libraryFunctionThatWeCantChange<T, "A" | "B", Partial<{ name: string; age: number }>>
>;

// 使用示例
const filler2: TargetSecondParam<"firstParameter"> = {
  label: "firstParameter",
  type: "B",
  person: { age: 25 }
};

方法三:包装成柯里化函数获得实时提示

通过柯里化包装函数,先传入第一个参数,后续传入第二个参数时自动获得类型提示:

const wrapLibrary = <T extends string>(firstArg: T) => {
  return (secondArg: Parameters<typeof libraryFunctionThatWeCantChange<T, "A" | "B", Partial<{ name: string; age: number }>>[1]) => {
    return libraryFunctionThatWeCantChange(firstArg, secondArg);
  };
};

// 使用时先传第一个参数,第二个参数自动带提示
const handleFirstParam = wrapLibrary("firstParameter");
const filler3 = { label: "firstParameter", type: "A", person: {} };
handleFirstParam(filler3);

原方法失效原因

直接使用Parameters<typeof libraryFunctionThatWeCantChange<"firstParameter">>[1]无效,是因为库函数包含多个泛型参数(Extra1、Extra2),仅指定T时TypeScript无法自动推断剩余泛型的类型,必须显式指定所有泛型参数或为其设置默认值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 16:45:47