The utility type Partial<Type> makes all properties of a type optional.
Using a scenario, let us try to understand Partial<T> in TypeScript. So, you have a type called Product, that is created as below:
export interface Product { Id: string; Title: string; Price: number; inStock: boolean; Quantity: number; }
And there is a function to update the price of a product as shown below:
updatePrice(p: Product, updatedProduct: Product){
// Implementation
}
To use the updatePrice function, you pass two objects of the type Product,
update(){
let product: Product = {
Id: "1",
Title: "Pen",
inStock: true,
Price: 300,
Quantity: 20
}
let productToUpdate: Product = {
Id: "1",
Title: "Pen",
inStock: true,
Price: 3000,
Quantity: 20
}
this.updatePrice(product, productToUpdate);
}
So far, this implementation looks fine. However, in the real scenario, to update the price of a product, you don’t necessarily have to create an object with value for all the fields of the Product. Ideally, you should only need ID and Price to update the price of a product, as shown below,
this.updatePrice(product, { Id: "1", Price: 3000 });
If you try to do so, clearly, TypeScript complains about the above code saying,
Argument of type ‘{ Id: string; Price: number; }’ is not assignable to parameter of type ‘Product’.
Now how could we fix it? There are three possible ways you can fix it.
- Change the type of updateProduct to any in the updatePrice function. But it is not suggestive because we must avoid using any as much as possible.
- Make fields optional in the Product type. Again, it is not a good idea.
- Use Partial type.
Let us modify updatePrice to use Partial type as shown below:
updatePrice(p: Product, updatedProduct: Partial<Product>){
// Implementation
console.log(p);
console.log(updatedProduct);
}
Now you can call the updatePrice function with just Id and Price fields, and TypeScript does not complain about that.
this.updatePrice(product, { Id: "1", Price: 3000 });
Partial<T> constructs a type with all properties of Type set to optional. This utility will return a type that represents all subsets of a given type.
In the TypeScript, Partial<T> is implemented as below; it makes properties optional.
type Partial<T> = { [P in keyof T]?: T[P]; };
In summary, whenever you need to make all properties optional, use the Partial<T> type. I hope you find this post helpful. Thanks for reading.
Discover more from Dhananjay Kumar
Subscribe to get the latest posts sent to your email.
Very informative