Imagine we have a scenario with an interface like this:
interface User {
Id: number;
FirstName: string;
Lastname: string;
Age: number;
Type: string;
}
and a specific method for copying properties based on a flag.
function copyIfAccepted<T extends object, K extends keyof T>(source: T, dest: T, key: K,
isAccepted: boolean) {
if (isAccepted && source[key] !== dest[key]) {
dest[key] = source[key];
}
}
Currently, the method is being called multiple times for each property. Keep in mind that not all properties are listed here.
copyIfAccepted(oldUser, newUser, 'Id', true);
copyIfAccepted(oldUser, newUser, 'FirstName', false);
copyIfAccepted(oldUser, newUser, 'LastName', true);
copyIfAccepted(oldUser, newUser, 'Age', true);
Is there a way to refactor this method so it only needs to be called once for all relevant properties? This should be done using TS 4.9