Type 'number' is not assignable to type 'never' when assigning to object's property

Viewed 61

TypeScript compiler gives me Type 'number' is not assignable to type 'never' error for the data[key] = 2; assignment in the code snippet below even though I explicitly check the type before the assignment (see on TypeScript Playground).

What is causing the error and what would be a proper way to manipulate all number properties of an object?

const data = {
  a: 1,
  b: 'b',
};

(Object.keys(data) as Array<keyof typeof data>).forEach((key) => {
  if (typeof data[key] === 'number') data[key] = 2;
});
0 Answers
Related