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

如何编写TypeScript函数签名以得到指定结构的返回类型?

解决方案

问题核心在于原代码里namedObject的name属性是宽泛的string类型,导致TypeScript无法把传入的具体字符串值推断为字符串字面量类型,最终返回类型变成{ [key: string]: number },而非预期的包含具体属性名的对象类型。

要让返回类型符合预期,需要修改函数签名,让泛型准确捕获每个参数name的字面量联合类型,具体写法如下:

写法一:直接泛型约束

declare function createObjectWithKey<T extends string>(
  ...namedObjects: { name: T }[]
): { [Key in T]: number };

调用createObjectWithKey({name: 'test'}, {name: 'test2'})时,TypeScript会自动将T推断为'test' | 'test2',返回类型即为:

{
  test: number;
  test2: number;
}

写法二:复用命名类型(可选)

如果需要复用namedObject类型,可以将其定义为泛型类型:

type NamedObject<T extends string = string> = {
  name: T;
};

declare function createObjectWithKey<T extends string>(
  ...namedObjects: NamedObject<T>[]
): { [Key in T]: number };

写法三:元组推断(更灵活)

如果需要支持更复杂的元组参数场景,可通过元组泛型提取每个元素的name类型:

declare function createObjectWithKey<T extends readonly { name: string }[]>(
  ...namedObjects: T
): { [Key in T[number]['name']]: number };

这种写法下,TypeScript会自动从元组参数中提取所有name的字面量类型并生成联合类型,最终返回同样符合预期的具名属性对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 07:35:00