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

通过泛型为类型添加自定义键的TypeScript实现问题

TypeScript 扩展函数返回类型问题

问题背景

现有以下TypeScript类型与函数:

interface Values {
  width: number;
  height: number;
};

interface Opts<T extends string> {
  requiredKeys: (keyof Values | NoInfer<T>)[];
  customParsers: Record<T, (text: string) => unknown>;
}

function example<T extends string>(opts: Partial<Opts<T>>): Partial<Values>;

期望example函数的返回类型能扩展Values,同时包含Opts['customParsers']中的键,比如:

example({
  customParsers: {
    x: text => parseInt(text),
  },
}); // 应返回类型:{ width?: number, height?: number, x?: number }

尝试了以下代码但未成功:

type Values<T extends Opts<string>> = {
  width: number;
  height: number;
} & {
  [K in keyof T]: ReturnType<T[K]>;
};

解决方案

要实现这个需求,需要调整函数的返回类型,通过泛型T提取customParsers的键,并将每个键对应的解析函数返回类型合并到Partial<Values>中。修改后的代码如下:

interface Values {
  width: number;
  height: number;
};

interface Opts<T extends string> {
  requiredKeys: (keyof Values | NoInfer<T>)[];
  customParsers: Record<T, (text: string) => unknown>;
}

// 调整返回类型:合并Partial<Values>和自定义键的可选类型
function example<T extends string>(
  opts: Partial<Opts<T>>
): Partial<Values> & { [K in T]?: ReturnType<Opts<T>['customParsers'][K]> };

// 函数实现(按需补充逻辑)
function example<T extends string>(opts: Partial<Opts<T>>) {
  // 此处编写实际解析逻辑
  return {} as any;
}

效果验证

调用示例中,TypeScript会正确推断返回类型包含自定义键的可选类型:

const result = example({
  customParsers: {
    x: text => parseInt(text),
  },
});
// result的类型为:{ width?: number; height?: number; x?: number; }

关键说明

  • 泛型T会自动捕获customParsers对象的键名
  • 通过ReturnType<Opts<T>['customParsers'][K]>获取每个解析函数的返回类型
  • 使用&运算符合并Partial<Values>与自定义键的可选类型,保证所有属性均为可选状态

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 16:30:00