Mastering TypeScript Utility Types: Boost Your Code Reusability
Learn how to use TypeScript utility types to write cleaner, reusable, and more maintainable code with practical examples for beginners.
TypeScript provides a powerful set of utility types that help you manipulate and transform types easily. These utility types are built-in generic types that improve code reusability and make your type declarations more flexible and efficient. In this tutorial, we'll explore some of the most commonly used utility types with simple examples to level up your TypeScript skills.
### 1. Partial
interface User {
id: number;
name: string;
email: string;
}
// Without Partial
const updateUser = (user: User) => {
// ... update logic
};
// With Partial
const updateUserPartial = (user: Partial<User>) => {
// Now user can have any subset of User properties
};
updateUserPartial({ id: 101 }); // valid
updateUserPartial({ name: "Alice" }); // valid### 2. Required
interface Product {
id: number;
name?: string;
price?: number;
}
const createProduct = (product: Required<Product>) => {
// Now 'name' and 'price' must be provided
};
createProduct({ id: 1, name: "Book", price: 29.99 }); // valid
// createProduct({ id: 2 }); // Error: name and price missing### 3. Pick
interface Employee {
id: number;
name: string;
department: string;
salary: number;
}
// Pick only 'id' and 'name'
type EmployeeName = Pick<Employee, "id" | "name">;
const employee: EmployeeName = {
id: 1,
name: "John"
// department and salary are not required
};### 4. Omit
type EmployeeWithoutSalary = Omit<Employee, "salary">;
const employeeNoSalary: EmployeeWithoutSalary = {
id: 2,
name: "Sara",
department: "HR"
// salary is omitted
};### 5. Record
type PageInfo = {
title: string;
};
// Mapping page names to their info
const pages: Record<string, PageInfo> = {
home: { title: "Home Page" },
about: { title: "About Us" },
contact: { title: "Contact" }
};### Summary TypeScript utility types simplify complex type transformations, reduce repetition, and help you write more maintainable code. Early mastery of `Partial`, `Required`, `Pick`, `Omit`, and `Record` will boost your productivity and keep your codebase clean. Try using these utility types in your projects to experience the benefits!