If you’re a TypeScript developer, and never heard of utility types, then you’re missing out.
Utility types are a set of built-in types that can be used to manipulate other types.
I’ll be covering the most used ones in this post.
Utility types for object types
Partial
The Partial
type allows you to make all properties of an object optional.
type User = {
name: string;
age: number;
};
type PartialUser = Partial<User>;
// this will be equal to { name?: string; age?: number; }
Required
The Required
type allows you to make all properties of an object required. The opposite of Partial
.
type User = {
name?: string;
age?: number;
};
type RequiredUser = Required<User>;
// this will be equal to { name: string; age: number; }
Omit
To remove a property from an object, we can use the Omit
type.
type User = {
name: string;
age: number;
};
type UserWithoutAge = Omit<User, "age">;
// this will be equal to { name: string; }
Pick
To pick a property from an object, we can use the Pick
type.
type User = {
name: string;
age: number;
};
type UserAge = Pick<User, "age">;
// this will be equal to { age: number; }
Readonly
The Readonly
type allows you to make all properties of an object readonly.
type User = {
name: string;
age: number;
};
type ReadonlyUser = Readonly<User>;
// this will be equal to { readonly name: string; readonly age: number; }
Utility types for union types
Exclude
The Exclude
type works with union types. It allows you to exclude a type from a union.
type User = "Guest" | "Admin" | "User";
type UserOnly = Exclude<User, "Guest" | "Admin">;
Extract
The Extract
type works with union types. It allows you to extract a type from a union.
type User = "Guest" | "Admin" | "User";
type UserOnly = Extract<User, "User">;
Utility types for functions
ReturnType
The ReturnType
type allows you to get the return type of a function.
function getUser() {
return {
name: "Siham",
age: 25,
};
}
type User = ReturnType<typeof getUser>;
// this will be equal to { name: string; age: number; }
Parameters
The Parameters
type allows you to get the parameters of a function.
function getUser(name: string, age: number) {
return {
name,
age,
};
}
type User = Parameters<typeof getUser>;
// this will be equal to [string, number]
This is not an exhaustive list of utility types, you can find the full list here.
If you have any suggestions or questions, feel free to reach out to me on Twitter or LinkedIn.