avatarDr. Derek Austin 🥳

Summary

The provided content discusses the use of the Partial utility type in TypeScript to make object properties optional, enhancing code flexibility and maintainability, and introduces a custom DeepPartial type for handling nested objects.

Abstract

TypeScript's Partial utility type is a key feature for developers who need to make all properties of an object type optional. This capability is crucial for creating functions that update objects in a flexible manner, allowing for partial updates without affecting other properties. The article delves into the syntax and application of Partial with practical examples, demonstrating how it can be used to define a function that updates a Todo object with only the provided fields. Furthermore, the article addresses the limitation of Partial with nested objects and introduces a DeepPartial custom utility type to recursively make all nested properties optional. This advanced technique is particularly useful for complex object structures where updates may be required at multiple levels of the object hierarchy. The article concludes by encouraging the adoption of Partial and DeepPartial in TypeScript projects to facilitate easier handling of object types and to promote more maintainable codebases.

Opinions

  • The author emphasizes the importance of Partial for creating flexible and maintainable TypeScript code.
  • The use of Partial is presented as a best practice for defining functions that update objects with optional properties.
  • The article suggests that understanding Partial and DeepPartial is essential for handling complex object types effectively in TypeScript.
  • The author provides additional resources for readers to understand related concepts, such as the spread operator and the rest parameter, indicating their relevance and utility in TypeScript development.
  • The creation of a DeepPartial type is shown as a proactive approach to overcome the limitations of the standard Partial type when dealing with nested objects.

How To Use Partial in TypeScript

Here’s how to get optional object properties in TS ☑

Photo by Jen Theodore on Unsplash

When working with TypeScript, sometimes we need to make all properties of an object type optional. This is where the Partial utility type comes into play. It’s a powerful tool that can help us create more flexible and maintainable code. In this article, we’ll explore how to use Partial in TypeScript to effectively make “partial” object types.

What is Partial?

Partial is a utility type provided by TypeScript that constructs a new type with all properties of the given type set to optional. It allows us to represent all possible subsets of a given type. Here’s the definition of Partial:

type Partial<T> = {
  [P in keyof T]?: T[P];
}

Using Partial

Let’s consider a simple example of using Partial. Suppose we have a type Todo that represents a to-do item, the classic frontend example:

type Todo = {
  title: string;
  description: string;
}

Now, let’s say we want to create a function that updates a Todo object by applying a set of updates. We could use the Partial utility type to make all the properties of Todo optional in the fieldsToUpdate parameter:

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",
})

In this example, the updateTodo function takes a Todo object and a Partial<Todo> object as its parameters. The Partial<Todo> object allows us to update only a subset of properties from the original Todo object.

By the way, if you need a quick refresher on the ... syntax used in the code above, I’ve written 2 articles on that subject you should check out:

Advanced Use Case: DeepPartial

While Partial works great for simple objects, it doesn’t handle nested objects as you might expect. For example, let’s consider a slightly more complex Todo interface with a nested object:

interface Todo {
  title: string;
  metadata: {
    createdAt: Date;
    updatedAt: Date;
  };
}

If we try to use Partial<Todo> here, only the top-level properties will become optional, not the properties of the nested metadata object. To make all properties optional recursively, we can create a custom DeepPartial utility type:

type DeepPartial<T> = {
  [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
}

Now, if we use DeepPartial<Todo>, all nested properties will also become optional:

function updateDeepTodo(todo: Todo, fieldsToUpdate: DeepPartial<Todo>) {
  // Implementation
}

const todo3 = {
  title: "finish report",
  metadata: {
    createdAt: new Date(),
    updatedAt: new Date(),
  },
}

const todo4 = updateDeepTodo(todo3, {
  metadata: {
    updatedAt: new Date(),
  },
})

With DeepPartial, we can now update any level of properties within the Todo object. Hopefully, you can start to see how this can be useful in TS: any valid subtype of the deeply-nested object is a valid DeepPartial.

Conclusion: Partial Utility Type in TypeScript ☑

The Partial utility type in TypeScript is an invaluable tool for making all properties of a type optional. It helps us create more flexible and maintainable code by allowing us to represent all possible subsets of a given type. And with the help of custom utility types like DeepPartial, we can extend its capabilities to handle even more complex scenarios. Embrace the optional properties and start using Partial in your TypeScript projects today to make handling object types so much easier.

Happy coding! ☑️

Photo by Florian Schmetz on Unsplash
Typescript
Programming
Web Development
Software Development
Software Engineering
Recommended from ReadMedium
avatarAnahit Vardevanyan
Design Patterns in React

Introduction

4 min read