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

TypeScript中如何访问使用索引类型定义的Interface索引属性?

TypeScript 数字索引类型字典使用示例

你的ComputedTotalLLDOptions属于以数字为键、固定结构对象为值的索引签名接口,以下是不同场景的使用参考:

基础初始化与单条访问

// 初始化符合接口定义的OrderForm对象
const myOrder: OrderForm = {
  model_id: 1001,
  total_lld: {
    1: { contribution: 3000, duration: 24, rent: 1500 },
    2: { contribution: 5000, duration: 36, rent: 1200 },
    5: { contribution: 2000, duration: 12, rent: 1800 }
  }
}

// 直接通过数字索引访问对应属性
const firstContribution = myOrder.total_lld[1].contribution; // 输出3000
const secondRent = myOrder.total_lld[2].rent; // 输出1200

全量遍历字典条目

因为Object.keys默认返回字符串类型的键,需要手动转成数字匹配索引类型定义:

// 遍历所有键值对
Object.entries(myOrder.total_lld).forEach(([keyStr, value]) => {
  const index = Number(keyStr);
  console.log(`索引${index}的租期为${value.duration}个月`);
})

// 只遍历索引键
Object.keys(myOrder.total_lld).forEach(keyStr => {
  const index = Number(keyStr);
  const currentEntry = myOrder.total_lld[index];
  // 后续自定义处理逻辑
})

类型安全优化建议

  • 原始接口默认认为任意数字索引都存在对应值,如果实际业务中可能出现空索引,建议给值加可选标记:
export interface ComputedTotalLLDOptions {
  [index: number]: {
    contribution: number;
    duration: number;
    rent: number;
  } | undefined;
}
  • 访问不确定是否存在的索引时,搭配可选链做安全校验:
// 索引不存在时返回undefined,不会触发运行时报错
const unknownEntryRent = myOrder.total_lld[999]?.rent;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 09:24:03