TypeScript utility types are a powerful feature that enhances type manipulation and transformation. They provide a set of built-in types to help developers create more flexible and reusable code.
Utility types in TypeScript are pre-defined generic types that perform common type transformations. They allow developers to modify existing types without creating new ones from scratch.
The Partial<T>
utility type makes all properties of a type optional.
interface User {
name: string;
age: number;
}
type PartialUser = Partial<User>;
// Equivalent to: { name?: string; age?: number; }
Contrary to Partial<T>
, Required<T>
makes all properties required.
interface Config {
debug?: boolean;
timeout?: number;
}
type RequiredConfig = Required<Config>;
// Equivalent to: { debug: boolean; timeout: number; }
The Pick<T, K>
utility type creates a new type by selecting a set of properties from an existing type.
interface Person {
name: string;
age: number;
address: string;
}
type NameAge = Pick<Person, 'name' | 'age'>;
// Equivalent to: { name: string; age: number; }
Omit<T, K>
creates a new type by removing specified properties from an existing type.
interface Product {
id: number;
name: string;
price: number;
description: string;
}
type ProductSummary = Omit<Product, 'description'>;
// Equivalent to: { id: number; name: string; price: number; }
TypeScript also provides more advanced utility types for complex scenarios:
Readonly<T>
: Makes all properties of a type readonly.Record<K, T>
: Creates an object type with keys of type K and values of type T.Exclude<T, U>
: Excludes types in U from T.Extract<T, U>
: Extracts types in U from T.Utility types are an essential part of TypeScript's type system. They provide a powerful way to manipulate and transform types, leading to more expressive and maintainable code. By mastering utility types, developers can write more robust and flexible TypeScript applications.
For more advanced type manipulations, explore Conditional Types and Mapped Types in TypeScript.