DEV Community 👩‍💻👨‍💻

Varit Patel
Varit Patel

Posted on

What is Partial & Required utility types in TypeScript?

In a real-world application, Basic types are used but there are scenarios where we need some types that can be derived from one or two types. TypeScript provides various utility types to make an easier transformation from the already defined type in our project. moreover, these utilities are globally available. Hence it can be accessed from anywhere.

Basic understanding of TypeScript requires in order to understand the below concept.

Partial<T>

  • Make a type with all properties of T set to Optional.
  • Useful when some of the properties of the type T to be updated.

interface Todo {
    title: string;
    description: string;
}

function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>): Todo {
    return { ...todo, ...fieldsToUpdate };
}

const todo1 = {
    title: 'organize desk',
    description: 'clear clutter',
};

const todo2 = updateTodo(todo1, {
    description: 'throw out trash',
});

Above example, <T> denotes as a defined type that needs to be modified.

Required<T>

  • Make a type with all properties of T set to Required.
  • Useful when all the properties of the object to set all the properties of T to be updated.

interface Todo {
    title: string;
    description?: string;
}

function updateTodo(todo: Todo, fieldsToUpdate: Required<Todo>): Todo {
    return { ...todo, ...fieldsToUpdate };
}

const todo1 = {
    title: 'organize desk',
    description: 'clear clutter',
};

const todo2 = updateTodo(todo1, {
    title: 'title updated',
    description: 'throw out trash',
});

Important Points to note

Below are the scenarios where these two utilities can have some tweaks.

  • Useful when strictNullChecks flag is enabled.
  • Works only on a single level, does not work with the nested level.

And weirdly, If at all, Partial & Required are used together, the outer most will take higher priority(not useful in an ideal scenario, but mentioned just to understand it better).

Top comments (0)

Classic DEV Post:

Visualizing Promises and Async/Await 🤯

async await