Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
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.
Partial<T>
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.
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 a User version where all properties become optional.updateUser can 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);
updateUserInfo accepts updates which has type Partial<User>, allowing passing only fields to be changed.
Function combines existing user object with updated data, creating a new object.
The Partial type makes code more flexible, allowing work with partially filled objects, which is especially useful when updating data or creating configuration objects.