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;
}
Tis narrower thanRecord<string, number>, such as{a: 123, b: 456}where the properties are numeric literal types then you want the compiler to complain about setting its properties to1.0when a certain condition is met if that makes more sense, this is a contrived example.