Utility types are built-in TypeScript helpers that transform types. They make your types more concise, flexible, and powerful, especially when working with component props, APIs, and state.
We’ll cover the key TypeScript types you’ll encounter and use regularly when writing React code.
Partial<T>
Makes all properties optional.
// Define the original full type
interface User {
id: string;
name: string;
age: number;
}
// Use Partial to make all fields optional
type UpdateUser = Partial<User>;
// You can now create an object with just some fields
const updatedUserInfo: UpdateUser = {
name: "Bob", // no need for id or age
};
// Simulate an update function where not all user data needs to change
const updateUser = (user: UpdateUser): void => {
// This function accepts any subset of the User fields
console.log("Updating user with:", user);
};
updateUser(updatedUserInfo); // Updating user with: { name: "Bob" }
Use Partial when you want to allow updating or creating objects without needing all fields up front.
Required<T>
Makes all properties required (the opposite of Partial<T>).