I have 2 types:
type Core = { a: boolean; b: number; c: string } type CoreOptions = { a?: boolean; b?: number; c?: string; }
In this example, CoreOptions is meant to have some, none, or all of the properties that Core has depending on the use case, but never to have a property that isn’t in Core.
I am trying to systematically tie them together so that as things evolve and Core gets new properties, I only have to change the type Core.
How can this be achieved?
Advertisement
Answer
To use a type, but make all properties optional, TypeScript has a Utility type called Partial
. Official Documentation
Example from the TypeScript Documentation:
interface Todo { title: string; description: string; } function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) { return { ...todo, ...fieldsToUpdate }; } const todo1 = { title: "organize desk", description: "clear clutter", }; const todo2 = updateTodo(todo1, { description: "throw out trash", });