Utility Types
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>
).
interface Props {
name?: string;
age?: number;
}
type AllRequired = Required<Props>;
const person: AllRequired = {
name: "Bob",
age: 42,
};
Pick<T, K>
“Give me a type with only these specific keys from the original.”
Creates a type by picking a subset of properties from another type.
interface User {
id: string;
name: string;
age: number;
email: string;
isAdmin: boolean;
}
// Pick only id and name
type UserPreview = Pick<User, "id" | "name">;
const userPreview: UserPreview = {
id: "123",
name: "Alice",
};
Omit<T, K>
The inverse of Pick<T>
. Removes specific properties from a type.
interface User {
id: string;
name: string;
email: string;
isAdmin: boolean;
}
type UserWithoutAdmin = Omit<User, "isAdmin">;
const user: UserWithoutAdmin = {
id: "1",
name: "Alice",
email: "[email protected]",
};
Record<K, T>
Constructs an object type where the keys K
have values of type T
.
type Status = "idle" | "loading" | "error";
type StatusMessages = Record<Status, string>;
const messages: StatusMessages = {
idle: "Nothing happening",
loading: "Loading...",
error: "Something went wrong",
};
Exclude<T, U>
Removes from T
the types that are assignable to U
.
type Roles = "admin" | "user" | "guest";
type NonGuest = Exclude<Roles, "guest">;
// "admin" | "user"
Extract<T, U>
Keeps only types from T
that are assignable to U
.
type AllRoles = "admin" | "user" | "guest";
type StaffRoles = Extract<AllRoles, "admin" | "user">;
// "admin" | "user"
NonNullable<T>
Removes null
and undefined
from a type.
type MaybeName = string | null | undefined;
type Name = NonNullable<MaybeName>; // string
ReturnType<T>
Gets the return type of a function.
function getUser() {
return {
id: "1",
name: "Alice",
};
}
type UserReturn = ReturnType<typeof getUser>;
// { id: string; name: string }
More can be found in the official documentation.
Last updated