I’m creating a function which takes a boolean indicator object like:
const fruits = {
apple: false,
banana: false,
orange: false,
mango: false,
};
And an array like ['apple', 'orange']
. It should return object similar in structure of input object
with properties in array turned true
.
I’ve these typescript functions to achieve it
// Helper function to type Object.Keys
const objectKeysTyped = <Obj extends object>(obj: Obj) => {
return Object.keys(obj) as (keyof Obj)[];
};
// Main function
const arrayToBoolIndicator = <Obj extends Record<string, boolean>>(
boolFramework: Obj,
arrayOfIncluded: (keyof Obj)[]
) => {
return objectKeysTyped(boolFramework).reduce(
(acc, cur) => {
// TS Error next line: Type 'boolean' is not assignable to type 'Obj[keyof Obj]'.
acc[cur] = arrayOfIncluded.includes(cur);
return acc;
},
{ ...boolFramework }
);
};
Why am I getting the TS error while I’m assigning original type to object’s property?