Search code examples
typescripttyping

Setting object fields in a loop in TypeScript


I have a Feature object (originally from database but in code below I simplified it) and I want to update it:

type Feature = {id: number, name: string, deletedAt?: Date}

const newData: Partial<Feature> & {id: number} = {
    id: 1, deletedAt: new Date()
};
const oldFeature: Feature = {
    id: 1, name: 'Abc', deletedAt: undefined
};

for (const key of Object.keys(newData) as (keyof Feature)[]) {
    oldFeature[key] = newData[key];
}

Both oldFeature[key] and newData[key] are of type string | number | Date | undefined. But of course for each given key in both objects the type will be one of those above and will be the same. Still, I'm not allowed to make an assignment oldFeature[key] = newData[key] because it gives an error:

Type 'string | number | Date | undefined' is not assignable to type 'never'.
Type 'undefined' is not assignable to type 'never'.ts(2322)

Why? And how to make it properly?


Solution

  • Ok, so using a loop is an overkill. All I needed to do is to use object spreading:

    const updated = {
        ...oldFeature,
        ...newData,
    }
    

    ...and the proper fields get updated as needed.