I have a specific object with key/value pairs that I need to iterate over using the entries() method of Object followed by a forEach() method of Array. However, I'm struggling to understand how to avoid a typescript error in this situation:
type objType = {
prop1: number | undefined;
prop2: number | undefined;
prop3: number | undefined;
};
const obj: objType = {
prop1: 2,
prop2: 0,
prop3: undefined,
};
//1st attempt
Object.entries(obj).forEach(([key, value]) => {
if (value === undefined || value < 5) obj[key] = 5;
});
//2nd attempt
Object.entries(obj).forEach(
([key, value]: [keyof objType, number | undefined]) => {
if (value === undefined || value < 5) obj[key] = 5;
}
);
In my first attempt, I let TypeScript infer the type of key
(→ string
) and value
(→ number|undefined
). Unfortunately, I encountered an error when trying to access obj[key]
:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'objType'. No index signature with a parameter of type 'string' was found on type 'objType'.
For my second attempt, I tried to enforce the type of key
to match the keys of obj
using the keyof
operator. Surprisingly, this type definition is not allowed and resulted in the following message:
Argument of type '([key, value]: [keyof objType, number | undefined]) => void' is not assignable to parameter of type '(value: [string, number | undefined], index: number, array: [string, number | undefined][]) => void'. Types of parameters '__0' and 'value' are incompatible. Type '[string, number | undefined]' is not assignable to type '[keyof objType, number | undefined]'. Type at position 0 in source is not compatible with type at position 0 in target. Type 'string' is not assignable to type 'keyof objType'.
I understand why the first attempt failed, but I'm puzzled by the issue in the second attempt. It seems like TypeScript is interpreting my intention incorrectly. How should I properly define the types in this scenario?