Oh boy, how did I not know about Partial until now? This is something all Typescripters need to know.
I'll use the example based on the official docs...
https://www.typescriptlang.org/docs/handbook/utility-types.html
Let's sasy you have a simple interface and instance...
interface Todo {
title: string;
description: string;
}
const todo1 = {
title: 'organize desk',
description: 'clear clutter',
};
How would we write a method that takes our instance of Todo and updates it with values from another Todo?
How about this?
function updateTodo(originalTodo: Todo, fieldsToUpdateTodo: any) {
return { ...originalTodo, ...fieldsToUpdateTodo };
}
const todo2 = updateTodo(todo1, {
description: 'throw out trash',
});
Not great. We had to type fieldsToUpdateTodo as any because if it was an Todo, we would need to set every property on the Todo interface. What if we only wanted to update description? Hence using any. I guess we could mark all properties in Todo as optional, but then we'd lose a lot of the typechecking that we love.
If we knew we only ever wanted to update description things are easier...
function updateTodoDescription(originalTodo: ITodo, description: string) {
return { ...originalTodo, description: description };
}
But this pattern isn't scaleable if we had many properties and wanted to arbitrarily update properties.
Let's cut to the chase. How can Partial help? Turns out it's simple, barely an inconvenience...
function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
return { ...todo, ...fieldsToUpdate };
}
Wrapping an object in Partial marks all the properties on that object as optional.
We can then call our updateTodo like this...
const todo2 = updateTodo(todo1, {
description: 'throw out trash',
});
We are not forced to set every property from the Todo interface. Our UpdateTodo method can then happily use the spread operator to merge the two Todo's.