Context: (optional)
I was experimenting with ways to enhance the usability of the update(person: Person)
function by allowing only a subset of properties to be updated. I considered two options:
- Passing the id explicitly as the first argument to the update method, followed by
Partial<Person>
orOmit<Person, 'id'>
as the second argument. - Keeping the update method's signature unchanged with only one input argument and ensuring that the object provided contains the
id
property.
Using Omit
seemed like a suitable choice to me, although the keys to omit could be any string value.
Question:
Why doesn't TypeScript enforce the specific value of the keys when using Omit
? Is there any valuable reason for this that I may be missing?
Take a look at the code below
export interface Person {
id: string;
age: number;
name: string;
}
type UpdatePerson = Omit<Person, 'whatEver'>; // Why does 'whatEver' not trigger compiler errors?
type UpdatePerson2 = Pick<Person, 'id'> & Partial<Person>; // This correctly enforces a valid key
type UpdatePerson3 = Pick<Person, 'thisDoesNotCompile'> & Partial<Person>; // This line fails compilation as that property is not part of the interface
Currently, I am proceeding with update(person: UpdatePerson)
and
type UpdatePerson = Pick<Person, 'id'> & Partial<Person>;
. This approach makes all properties optional while making the id mandatory.