Search code examples
javascripttypescript

Error in reduce in typescript. Element implicitly has an 'any' type because expression of type


I have this code. Basically, it is an object of grades of students.

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;
}, {});

The error I'm getting:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. No index signature with a parameter of type 'string' was found on type '{}'

The expected output should be: The 111 is just a dummy data. Im gonna put some more relevant data there.

{1: 111, 2: 111}

Thanks in advance.


Solution

  • I think the number that you are using is converted to string, so you can just use the string as key (though it's not related to the issue here) You can solve the issue by adding

    {} 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);