Do you know all these Typescript Utility Types?
Rajae Robinson
Posted on October 13, 2023
Hey everyone,
I recently wrote an article exploring TypeScript's utility types. These are predefined type transformations that simplify working with types. These types are based on generics, enabling flexible and reusable type parameters. They allow developers to perform common type manipulations, making type definitions more efficient and readable. Here are some you should know:
1.Partial<Type>
Makes all properties of a given type optional.
type User = { id: number; name: string; email: string; };
type PartialUser = Partial<User>;
// Resulting type: { id?: number; name?: string; email?: string; }
2.Required<Type>
Enforces all properties of a given type to be required.
type PartialUser = {
id?: number;
name?: string;
email?: string;
};
type RequiredUser = Required<PartialUser>;
// Resulting type: { id: number; name: string; email: string; }
3.Readonly<Type>
Makes all properties of a given type readonly.
type MutableUser = {
id: number;
name: string;
};
type ImmutableUser = Readonly<MutableUser>;
// Resulting type: { readonly id: number; readonly name: string; }
4.Record<Keys, Type>
Constructs an object type with specified keys and a given value type.
type Weekdays = 'Monday' | 'Tuesday' | 'Wednesday' | 'Thursday' | 'Friday';
type Workload = Record<Weekdays, number>;
// Resulting type: { Monday: number; Tuesday: number; Wednesday: number; Thursday: number; Friday: number; }
5.Pick<Type, Keys>
Selects a subset of properties from a given type.
type User = {
id: number;
name: string;
email: string;
age: number;
};
type UserSummary = Pick<User, 'id' | 'name'>;
// Resulting type: { id: number; name: string; }
6.Omit<Type, Keys>
Excludes specified properties from a given type.
type User = {
id: number;
name: string;
email: string;
age: number;
};
type UserWithoutAge = Omit<User, 'age'>;
// Resulting type: { id: number; name: string; email: string; }
7.Exclude<Type, ExcludedUnion>
Generates a new type by excluding types from the first type that are assignable to any type in the second type.
type AllColors = 'red' | 'blue' | 'green' | 'yellow';
type PrimaryColors = 'red' | 'blue';
type NonPrimaryColors = Exclude<AllColors, PrimaryColors>;
// Resulting type: 'green' | 'yellow'
That's not all! The article also covers four more utility classes, custom utility types, and conditional types, providing examples for creating and leveraging them. These utility types enhance code readability, maintainability, and reusability.
Posted on October 13, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.