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

TypeScript如何给对象动态属性键设置指定命名规则约束?

解决方案

TypeScript 4.1及以上版本支持模板字面量类型作为索引签名的键类型,可以完美解决你提到的两个问题:

  1. 严格限制可选属性的命名规则
  2. 支持符合规则的属性名自动补全

最优类型定义

interface IResponse {
    // 三个必填固定属性
    id: number;
    name: string;
    isAdmin: boolean;
    // 限制可选属性必须为 property+数字的格式,值类型可根据实际业务调整为需要的联合类型
    [key: `property${number}`]: string;
}

效果验证

// 无报错,符合规则
const response1: IResponse = {
    id: 1,
    name: 'foo',
    isAdmin: true,
}

// 无报错,符合规则
const response2: IResponse = {
    id: 1,
    name: 'foo',
    isAdmin: true,
    property1: 'any string...'
}

// 无报错,符合规则
const response3: IResponse = {
    id: 1,
    name: 'foo',
    isAdmin: true,
    property1: 'any string...',
    property2: 'any string...'
}

// 抛出类型错误:对象字面量只能指定已知属性,类型"IResponse"中不存在属性"grade"
const response4: IResponse = {
    id: 1,
    name: 'foo',
    isAdmin: true,
    grade: 'A'
}

其他适配场景

如果property开头的属性值可能存在多种类型,可以调整索引签名的值类型为对应的联合类型即可,例如:

interface IResponse {
    id: number;
    name: string;
    isAdmin: boolean;
    // 支持字符串、数字、布尔三种值类型
    [key: `property${number}`]: string | number | boolean;
}

如果使用的TypeScript版本低于4.1,无法使用模板字面量索引,可以预定义最大支持的property序号上限,使用交叉类型实现:

// 示例支持到property20,可根据业务需要扩展联合类型的取值范围
type IResponse = {
    id: number;
    name: string;
    isAdmin: boolean;
} & Partial<Record<`property${1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20}`, string>>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 22:36:03