打字稿中的reduce错误。元素隐式具有“任意”类型,因为类型的表达式

问题描述 投票:0回答:2

我有这个代码。基本上,它是学生成绩的对象。

let students: {
  [k: number]: string[]
} = {};

students[1] = ["Student 1", "Student 2"];
students[2] = ["Student 3", "Student 4"];

console.log(students);

Object.keys(students).reduce((c, v) => {
  c[v] = 111; //Im assigning some values here. THE ERROR IS POINTING HERE

  return c;
}, {});

我遇到的错误:

元素隐式具有“任意”类型,因为类型的表达式 “string”不能用于索引类型“{}”。 没有带有 a 的索引签名 在类型“{}”上找到“字符串”类型的参数

预期输出应该是:

111
只是一个虚拟数据。我会在那里放一些更多相关数据。

{1: 111, 2: 111}

提前致谢。

javascript typescript
2个回答
1
投票

我认为您使用的数字已转换为字符串,因此您可以仅使用字符串作为键(尽管它与此处的问题无关) 您可以通过添加来解决问题

{} as { [k: string]: any }
type Student = {
  [k: string]: string[];
};

let students: Student = {};

students[1] = ["Student 1", "Student 2"];
students[2] = ["Student 3", "Student 4"];

console.log(students);

const keys = Object.keys(students);

const foo = keys.reduce(
  (c, v) => {
    c[v] = 111;

    return c;
  },
  {} as { [k: string]: any },
);

console.log("foo", foo);

0
投票

您需要设置“v”的类型,因为字符串不能用作索引类型,例如。 Object.keys(学生).reduce((c, v) => { c[v 作为学生密钥的类型] = 111;

返回c; }, {});

© www.soinside.com 2019 - 2024. All rights reserved.