Utility type partial in TypeScript
Partial is a utility type in TypeScript that makes all object properties optional. It's especially useful when you need to create a version of an existing type but with the ability to omit some fields.
Syntax
Partial<T>- T — original object type.
The Partial type creates a new type where all properties of T become optional. This is useful in situations where an object can be partially filled, for example, when updating data.
When to use Partial?
- When updating data (not all fields may be changed).
- For working with forms where user can fill only part of data.
- In API requests where only changed data is passed.
Partial Usage Examples
Creating a partial object based on existing type:
Suppose we have a User type and we want to create an object containing only some of its fields.
type User = {
id: number;
name: string;
email: string;
};
type PartialUser = Partial<User>;
const updateUser: PartialUser = {
name: "Alice",
};Partial<User>creates aUserversion where all properties become optional.updateUsercan contain only name, without needing to specify id or email.
Using Partial for object updates:
In data update functions it's convenient to use Partial to pass only changed properties.
function updateUserInfo(user: User, updates: Partial<User>): User {
return { ...user, ...updates };
}
const user: User = { id: 1, name: "Bob", email: "bob@example.com" };
const updatedUser = updateUserInfo(user, { name: "Robert" });
console.log(updatedUser);updateUserInfoaccepts updates which has typePartial<User>, allowing passing only fields to be changed.- Function combines existing user object with updated data, creating a new object.
Summary
The Partial type makes code more flexible, allowing work with partially filled objects, which is especially useful when updating data or creating configuration objects.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.