Umbrella
Umbrella

Reputation: 1145

Typescript doesn't infer value of generic object

Consider this function, it iterates over the provided object's keys and sets each key to a number and then returns the object. For some reason, typescript doesn't infer that obj[key] value is a number, I'm getting the following error:

Type '1' is not assignable to type 'T[keyof T]'.ts(2322)

Does anyone know how to fix this? Parameter should always be be Record<string, number>.

function setObjKeysToOne<T extends Record<string, number>>(obj: T) {
  (Object.keys(obj) as Array<keyof typeof obj>).forEach((key) => {
    obj[key] = 1; // Type '1' is not assignable to type 'T[keyof T]'.ts(2322)
  });

  return obj;
}

Upvotes: 1

Views: 716

Answers (1)

groetzi
groetzi

Reputation: 198

you could cast the obj during the assignment e.g.

function setObjKeysToOne<T extends Record<string, number>>(obj: T) {
  Object.keys(obj).forEach((key) => {
    (obj as Record<string, number>)[key] = 1;
  });

  return obj;
}

there's a related issue on github with an explanation why typescript behaves that way.

Upvotes: 1

Related Questions