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

如何为数组指定按索引匹配的固定元素类型?(TypeScript)

实现索引固定类型的数组

完全可以实现,你需要的是TypeScript元组类型结合泛型来定义每个索引位置的具体类型,而非使用联合类型。

解决方案

  1. 先定义你需要的具体类型:
type TypeA = { test: "testOne", values: Array<{ value: number; text: string }> };
type TypeB = { test: "testTwo", values: Array<{ value: number; text: string }> };
  1. 定义支持可变类型参数的ArrayTypes泛型,直接映射为元组:
// 支持任意数量的类型参数,每个参数对应数组的一个索引类型
type ArrayTypes<T, ...Rest extends any[]> = [T, ...Rest];
  1. 使用方式完全符合你的需求:
let arr: ArrayTypes<TypeA, TypeB> = [
  {
    test: "testOne",
    values: [{ value: 1, text: "ho" }]
  },
  {
    test: "testTwo",
    values: [{ value: 2, text: "hey" }]
  }
];

效果验证

  • 数组第一个元素必须严格匹配TypeA类型,第二个元素必须严格匹配TypeB类型,TypeScript会对类型不匹配的情况直接报错。
  • 完全避免了联合类型的模糊性,每个索引的类型是硬编码的固定类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 02:37:39