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

如何在TypeScript接口中添加已知属性与前缀匹配动态属性

TypeScript 动态属性接口定义方案

你可以利用TypeScript 4.4及以上版本支持的模板字符串索引签名,在保留原有已知属性的同时,精准约束两类动态属性的命名前缀和类型:

// 先假设你已定义以下依赖类型
interface ApplicantData {}
interface ApplicationUnit {}
interface InterestedPerson {}
interface Expenses {}

export interface ApplicationData {
  applicant?: ApplicantData;
  application_unit?: ApplicationUnit;
  interested_people_count?: number;

  // 约束以 'interested_person_' 开头的属性类型为 InterestedPerson
  [key: `interested_person_${string}`]: InterestedPerson;
  // 约束以 'expenses_' 开头的属性类型为 Expenses
  [key: `expenses_${string}`]: Expenses;
}

说明

  • 原有已知属性完全保留,类型约束不受影响
  • 模板字符串索引会自动校验属性名:只有前缀匹配的属性才能被添加,且必须符合对应类型要求
  • 如果动态属性是可选的(允许不存在),可以把类型改为InterestedPerson | undefined或Expenses | undefined

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 22:52:01