TypeScript索引类型错误:如何正确声明颜色对象变量?
正确的TypeScript类型声明方式
错误原因是object类型未定义字符串索引签名,TypeScript无法推断字符串索引对应的值类型,因此抛出类型错误。你需要明确定义colorsNames的类型结构:
- 先定义单个颜色值的类型:
type RGBColor = { r: number; g: number; b: number; };
- 用以下两种方式之一声明
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
相关产品推荐
相关产品推荐

