Make every property optional with Partial
Partial of T makes every property optional, which suits update functions that take only the fields that change. Available since TypeScript 2.1.
An update function should accept { email } without asking for the whole user again. Partial<User> is User with every property turned optional.
interface User {
id: number;
name: string;
email: string;
}
function updateUser(user: User, changes: Partial<User>): User {
return { ...user, ...changes };
}
const ada: User = { id: 1, name: 'Ada', email: '[email protected]' };
console.log(updateUser(ada, { email: '[email protected]' }));{ id: 1, name: 'Ada', email: '[email protected]' }Partial<T> is a mapped type, { [K in keyof T]?: T[K] }, so it adds a ? to each property and nothing else. The object spread then lets the supplied fields win.
It is shallow: a Partial<User> with a nested address still requires a complete address object when you provide one. Also, { email: undefined } is a valid Partial<User> and the spread will overwrite the real email with undefined, so strip undefined values if callers can pass them. Turn on exactOptionalPropertyTypes to make that explicit.