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

如何参数化带自动补全的TypeScript索引签名类型?

解决方案:指定属性类型并自动推断对象结构的TypeScript通用函数

你需要的是一个既能约束对象属性类型,又能自动推断对象具体结构的通用函数,无需为每种属性类型单独创建函数,也不用手动传入所有泛型参数。以下是实现方案:

核心实现代码

export const Intended_Autocompletion_Record = <Type, T extends Record<string, Type> = Record<string, Type>>(arg: T): T => {
    return arg;
};

使用示例

正确用法

指定属性类型为string,TypeScript会自动推断对象的具体结构(包含属性名),同时提供类型补全:

const intended_usage = Intended_Autocompletion_Record<string>({first: "string", second: "another"});
// 鼠标悬停intended_usage可看到类型为:{ first: string; second: string; }

错误用法

若传入不符合指定类型的属性,TypeScript会直接抛出类型错误:

// 报错:类型'number'不能赋值给类型'string'
const invalid_usage = Intended_Autocompletion_Record<string>({first: "string", second: 42});

原理说明

  • 泛型参数Type:用于手动指定对象所有属性的允许类型,调用时只需传入该参数(如<string>)。
  • 泛型参数T:被约束为Record<string, Type>,确保对象的所有属性都符合指定的Type;同时设置默认值Record<string, Type>,让TypeScript可以自动推断传入对象的具体结构(保留属性名),无需手动传入T。
  • 返回值类型为T:保留了对象的精确结构类型,而非宽泛的Record<string, Type>,完美支持类型自动补全。

可选柯里化写法

如果你偏好链式调用风格,也可以用柯里化方式实现:

export const Intended_Autocompletion_Record = <Type>() => <T extends Record<string, Type>>(arg: T): T => {
    return arg;
};

// 调用方式
const intended_usage = Intended_Autocompletion_Record<string>()({first: "string", second: "another"});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 07:47:25