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
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.
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 1–4: 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 7–10: 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.
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 9–12: 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