Imagine having a structure like this
interface User {
name: string;
email: string;
}
along with a function like this
updateUser(user: User) {
}
As currently defined, updateUser
cannot accept only a name (updateUser({name: 'Anna'}
would fail) if that is the sole property intended for updating.
Making email
optional in the User
interface could solve this issue, but it's not an ideal solution. The expectation should be that when someone receives a User object, all fields are present.
One possible solution is to change the type of updateUser
to:
updateUser(user: {name?: string, email?: string}) {
}
This approach works, but requires repeating the entire user object and updating both declarations whenever new properties are added to the User
interface.
Is there a way to define updateUser
so that it allows specific parts of a user object, while still rejecting missing or incorrectly typed properties?