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

TypeScript索引类型错误:如何正确声明颜色对象变量?

正确的TypeScript类型声明方式

错误原因是object类型未定义字符串索引签名,TypeScript无法推断字符串索引对应的值类型,因此抛出类型错误。你需要明确定义colorsNames的类型结构:

  1. 先定义单个颜色值的类型:
type RGBColor = {
  r: number;
  g: number;
  b: number;
};
  1. 用以下两种方式之一声明colorsNames:
  • 使用Record工具类型(更简洁):
let colorsNames: Record<string, RGBColor>;
  • 直接定义索引签名:
let colorsNames: { [key: string]: RGBColor };

完整示例代码:

type RGBColor = {
  r: number;
  g: number;
  b: number;
};

let colorsNames: Record<string, RGBColor>;

fetch('colorNames.json')
  .then(response => response.json())
  .then(data => {
    colorsNames = data;
    // 遍历调用getDistance的示例
    for (const name in colorsNames) {
      const { r, g, b } = colorsNames[name];
      getDistance(r, g, b);
    }
  });

这样TypeScript就能准确识别colorsNames的键值对类型,不会再抛出索引类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 17:22:34