I am trying to create a generic function that will only update values of type object within a map, and ignore anything else.
Is it possible to achieve this? I have looked for a solution but haven't found one yet.
enum SKey {
key1 = "key1",
key2 = "key2",
}
type SItem = {
[SKey.key1]: boolean;
[SKey.key2]: {
attr1: string;
attr2: boolean;
};
};
const mapDB: SItem = {
[SKey.key1]: true,
[SKey.key2]: {
attr1: "hello",
attr2: true,
},
};
export function updateDbItem<K extends keyof SItem>(
key: K,
newFields: Partial<SItem[K]>
) {
const item: SItem[K] = mapDB[key];
mapDB[key] = { ...item, ...newFields };
}
However, I am encountering the following error:
error TS2698: Spread types may only be created from object types.
mapDB[key] = { ...item, ...newFields };
~~~~~~~~
Would appreciate any help or suggestions on how to resolve this issue. Thank you!