I don’t get why this code raises TS2532: Object is possibly 'undefined'. Why obj[prop] check is not enough and what is the proper way of writing this logic?
function test<T extends string>(obj: Record<T, number | undefined>, prop: T) {
if (obj[prop]) obj[prop]--;
}
>Solution :
Typescript can’t handle the generics that well which is described in ms/TS#33014. Example:
function f<T extends 'a' | 'b'>(x: T) {
if (x === 'a') {
x; // T extends "a" | "b"
}
}
The easiest solution would be to store obj[prop] in a separate variable and if that value exists then assign a new value to obj[prop]:
function test<T extends string>(obj: Record<T, number | undefined>, prop: T) {
let value = obj[prop];
if (value) {
obj[prop] = value - 1;
}
}