The Partial type in TypeScript is a utility type which does the opposite of Required. It sets all properties in a type to optional.
Let's look at how it works. If you're interested in the opposite problem, try my article on how the Required type works in TypeScript.
Partial Type in TypeScript
In TypeScript, we can define a type as optional with a ? question mark. For example, in the below code, lastName is optional. Therefore, even though firstUser has the type User, we can leave out lastName as it is not required.
type User = {
firstName: string,
lastName?: string
}
let firstUser:User = {
firstName: "John"
}
Sometimes, the type we inherit or use has no optional types, but we know that in certain circumstances some properties might be missing. Take a look at the following example. Here, lastName is not optional anymore, but firstUser still doesn't have it:
type User = {
firstName: string,
lastName: string
}
let firstUser:User = {
firstName: "John"
}
This code throws an error, since it is expecting that firstUser of type User should have a property called lastName
:
Property `lastName` is missing in type `{ firstName: string; }` but required in type `User`.
If we want to avoid that error, we have to change firstUser's type to Partial<User>
. That will tell TypeScript to set every property in the type User to optional:
type User = {
firstName: string,
lastName: string
}
let firstUser:Partial<User> = {
firstName: "John"
}
This is ultimately the same as redefining the User type to:
type User = {
firstName?: string,
lastName?: string
}
The only difference is, we can now use both - if we want the type to have some missing properties, we can use Partial. If we don't, we can just use the normal User type:
type User = {
firstName: string,
lastName: string
}
let firstUser:Partial<User> = { firstName: "John" }
let secondUser:User = { firstName: "John", lastName: "Doe" }
As with many other utility types in TypeScript, Partial is meant to work with interfaces or custom types defined as objects like our User type above. So it won't work on things like variables.
If you've enjoyed this quick guide, check out more TypeScript content here.
Top comments (3)
Partial
is my go to type in styled components.Thanks
I didn't know that yet!
Thanks for sharing