Utility types in TypeScript are a set of predefined generic types that help in various type manipulation tasks. They can be used to create new types based on existing types by modifying, picking, or omitting some parts of them. This powerful feature helps in making the code more maintainable, scalable, and robust by reusing existing types and keeping the type definitions DRY (Don’t Repeat Yourself).
Here are some common utility types in TypeScript with their respective usage examples:
1. ‘Partial<T>‘: Constructs a new type with all properties of ‘T‘ set as optional.
interface Person {
name: string;
age: number;
}
type PartialPerson = Partial<Person>;
const person: PartialPerson = {
name: 'John',
};
2. ‘Readonly<T>‘: Constructs a new type with all properties of ‘T‘ set as readonly.
interface Person {
name: string;
age: number;
}
type ReadonlyPerson = Readonly<Person>;
const person: ReadonlyPerson = {
name: 'John',
age: 30,
};
person.age = 31; // Error: Cannot assign to 'age' because it is a read-only property
3. ‘Pick<T, K>‘: Constructs a new type by picking a set of properties ‘K‘ from ‘T‘.
interface Person {
name: string;
age: number;
email: string;
}
type PersonNameAndEmail = Pick<Person, 'name' | 'email'>;
const person: PersonNameAndEmail = {
name: 'John',
email: 'john@example.com',
};
4. ‘Omit<T, K>‘: Constructs a new type by omitting a set of properties ‘K‘ from ‘T‘.
interface Person {
name: string;
age: number;
email: string;
}
type PersonWithoutEmail = Omit<Person, 'email'>;
const person: PersonWithoutEmail = {
name: 'John',
age: 30,
};
5. ‘Record<K, T>‘: Constructs a new type with a set of property keys ‘K‘ and corresponding value type ‘T‘.
type UserRole = Record<'admin' | 'user', string>;
const roles: UserRole = {
admin: 'Administrator',
user: 'Regular User',
};
6. ‘Exclude<T, U>‘: Constructs a new type by excluding values from ‘U‘ that are assignable to ‘T‘.
type T1 = Exclude<'a' | 'b' | 'c', 'a'>; // Result: 'b' | 'c'
7. ‘Extract<T, U>‘: Constructs a new type by extracting values from ‘U‘ that are assignable to ‘T‘.
type T1 = Extract<'a' | 'b' | 'c', 'a' | 'f'>; // Result: 'a'
8. ‘NonNullable<T>‘: Constructs a new type by excluding ‘null‘ and ‘undefined‘ from ‘T‘.
type T1 = NonNullable<string | number | null | undefined>; // Result: string | number
These utility types can be combined and customized according to the requirements of your projects, making the type handling in TypeScript more flexible and powerful.