How to use the TypeScript Partial Type

In TypeScript, the Partial<T> type allows you to create a new type with all the properties of type T, but with all properties set to optional. This can be useful when you want to use an interfaceAn interface in TypeScript is a blueprint that describes the structure of an object. that may not require all fields to be populated.

If you don't use Partial<T>, you would need to provide values for all fields in an interface, even in cases where those fields are not relevant or don't exist.

Working without Partial<T>

Consider the following scenario where the address property is missing, and the Partial<T> type is not used:

interface Person {
name: string;
age: number;
address: string;
}
const newPerson: Person = {
name: 'John',
age: 25,
};
console.log(newPerson)
  • Lines 14: An interface named Person is defined. It contains three different properties: name of type string, age of type number, and address of type string.

  • Lines 710: A new variable named newPerson is assigned an object value that has two properties: name with the string value 'John' and age with the number value 25.

Note that the address property is not provided in the assigned object newPerson. This code will result in a TypeScript error. To make the address property optional, we can use the Partial<T> type.

Working with Partial<T>

The Partial<T> type is used when creating types to make all properties of a type optional. This is helpful in scenarios where you don't need to provide values for all properties. Here's an example illustrating the usefulness of Partial<T>:

interface Person {
name: string;
age: number;
address: string;
}
type PartialPerson = Partial<Person>;
const partialPerson: PartialPerson = {
name: 'John',
age: 25,
};
console.log(partialPerson)
  • Line 7: A type name PartialPerson is created using the Partial<T> type. This type represents a new type with the same structure as the Person interface but with all properties set to optional.

  • Lines 912: The variable partialPerson is assigned an object with two properties: name and age. The address property is optional in this case. T

By using Partial<T>, you can attain flexibility by making properties optional according to the original interface. This enables easier handling of partial data or situations where not all properties are mandatory.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved