skip to Main Content

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.

2

Answers


  1. You need to set what type the ‘v’ because the string can not be used as index type, eg.

    Object.keys(students).reduce((c, v) => {
      c[v as typeOf keyOf students] = 111;
    
      return c;
    }, {});
    
    Login or Signup to reply.
  2. 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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search