Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript – make one type equal to another but with its properties being optional

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can this be achieved?

>Solution :

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",
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading