Objects 16 exercises
solution

The Partial Utility Type in TypeScript

The Partial utility type in TypeScript can convert an object's properties to optional.

Here's an example of how it works with the Product interface:


interface Product {
id: number;
name: string;
price: number;
description: string;
}
type PartialProduct = Partial<Product>;
``

Loading solution

Transcript

00:00 Okay, the type helper in question is partial. Partial basically takes in, so we can say partial product equals partial, and it takes in an object, which is the object that you want to make all optional. If you hover over this, you can see that now each property, ID, name, price, description,

00:19 are all string or undefined, which is super nice. So all we need to do in order to make this work for product info here, is just wrap this update product or omits product ID with a partial. Now, product info is a partial of omits product ID. You notice how these angle brackets

00:38 kind of stack up with each other, and now everything works. Of course, this does mean that we can pass in zero properties, but I guess this maybe should be a legal operation, I don't know. But that's kind of an edge case really, and that's sort of down to the user who's using it. And you can see here that we get still autocomplete for all of the members. And if we hover over update product,

00:57 it's got partial omit product ID inside there. So partial can be used in a bunch of different situations when you want to make any object optional.