在类型 "{ 1: number; 4: number; 5: number; 8: number; }" 上找不到具有类型为 "number" 的参数的索引签名
在 TypeScript 中,当你使用一个类型为 number 的表达式来索引一个对象时,该对象的索引类型必须是明确定义的。如果索引类型为 "{ 1: number; 4: number; 5: number; 8: number; }",那么只能用 1、4、5、8 这些特定的数字来作为索引,而不能使用任意的 number 类型。
要解决这个问题,你可以通过修改对象的类型定义或者使用类型断言来告诉 TypeScript 编译器确切的索引类型。以下是两种解决方法:
方法一:修改对象的类型定义
interface MyObject {
[key: number]: number;
}
const myObject: MyObject = { 1: 10, 4: 20, 5: 30, 8: 40 };
const index: number = 1;
const value = myObject[index]; // 现在 TypeScript 将不会报错
方法二:使用类型断言
const myObject: { [key: number]: number } = { 1: 10, 4: 20, 5: 30, 8: 40 };
const index: number = 1;
const value = myObject[index as keyof typeof myObject]; // 使用类型断言告诉 TypeScript 编译器确切的索引类型
通过以上方法,你可以解决 "类型为 'number' 的表达式不能用于索引类型 '{ 1: number; 4: number; 5: number; 8: number; }'" 的错误。