提问人:Greg 提问时间:9/19/2023 最后编辑:Greg 更新时间:9/19/2023 访问量:32
在类型“{}”上未找到类型为“string”的参数的索引签名 - TypeScript
No index signature with a parameter of type 'string' was found on type '{}' - TypeScript
问:
我从文件中读取键值对,键是字符串,值是 {r,g,b} 个数字。
colorNames.json文件:
{
"name1": { "r": 151, "g": 23, "b": 26 },
"name2": { "r": 62, "g": 137, "b": 32 },
"name3": { "r": 13, "g": 31, "b": 62 },
}
fetch("/colorNames.json")
.then((res) => res.json())
.then((data) => {
colorsNames = data;
});
当我将值传递给函数时,出现以下错误:
元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引类型“{}”。 在类型“{}”上未找到参数类型为“string”的索引签名。
for (let key in colorsNames) {
let distance = getDistance(color, colorsNames[key]);
}
function getDistance(
color: { r: number; g: number; b: number },
match: { r: number; g: number; b: number }
)
另外,将 colorsNames 声明为的正确方法是什么?
var colorsNames: object;
答:
0赞
jcalz
9/19/2023
#1
看起来您想要一个索引签名,以便您可以使用任何值键索引到其中。喜欢这个:colorsNames
string
string
const colorsNames: { [k: string]: { r: number, g: number, b: number } } = {
"name1": { "r": 151, "g": 23, "b": 26 },
"name2": { "r": 62, "g": 137, "b": 32 },
"name3": { "r": 13, "g": 31, "b": 62 },
};
在这里,您说在键为 type 的每个属性中,您都有一个 type 值(您可能想给它起个名字,比如 ,但这是一个题外话)。string
{r: number, g: number, b: number}
interface Color {r: number, g: number, b: number}
现在,您可以根据需要循环访问其属性:
for (let key in colorsNames) {
let distance = getDistance(color, colorsNames[key]); // okay
}
评论
1赞
Greg
9/19/2023
谢谢,我是 TypeScript 的新手,我怀疑声明 as 不会削减它。是的,我应该为此使用接口。colorsNames
object
评论