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

TypeScript映射类型报错:C[number]无法索引ConfigurableFieldsType<C>

解决Type 'C[number]'无法索引ConfigurableFieldsType的问题

问题原因

你的ConfigurableFieldsType<T>类型定义逻辑错误:[field in keyof T]遍历的是数组类型T的索引键(比如"0"、"1"这类字符串形式的数字索引),而非数组元素本身的字符串值。但你在方法中使用C[number](数组元素的字符串类型)去索引该类型对象,两者类型不匹配,因此触发报错。

解决方案

修改ConfigurableFieldsType的定义,将遍历目标改为数组的元素类型T[number],让类型的键直接对应数组元素的字符串值:

export type ConfigurableFieldsType<T extends string[]> = {
  [field in T[number]]: string
}

完整修正代码

export type ProductType<T extends string[]> = {
  // more variables
  configurableFields: ConfigurableFieldsType<T>
}

export type ConfigurableFieldsType<T extends string[]> = {
  [field in T[number]]: string
}

export class Product<C extends string[]> implements ProductType<C> {
  constructor(
    // more public parameters
    public configurableFields: ConfigurableFieldsType<C>,
  ) {}

  private getConfigurableAttribute(attribute: C[number]): string {
    return this.configurableFields[attribute]
  }
}

修改后,ConfigurableFieldsType<C>的键类型与方法参数C[number]完全匹配,索引类型不匹配的报错会自动消失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 06:57:16