Utility Types in TypeScript (Live Playground)
In this tutorial, we will explore utility types in TypeScript. Understanding how to use utility types will help you write more flexible and type-safe code.
Utility types are built-in generic types provided by TypeScript that can be used to perform common operations on types.
Partial<Type>
The Partial
utility type creates a new type with all the properties of the original type set as optional:
interface Person {
name: string;
age: number;
}
type PartialPerson = Partial<Person>;
const partialPerson: PartialPerson = { name: 'John Doe' };
Readonly<Type>
The Readonly
utility type creates a new type with all the properties of the original type set as readonly:
interface Person {
name: string;
age: number;
}
type ReadonlyPerson = Readonly<Person>;
const readonlyPerson: ReadonlyPerson = { name: 'John Doe', age: 30 };
readonlyPerson.age = 31; // Error: Cannot assign to 'age' because it is a read-only property
Pick<Type, Keys>
The Pick
utility type creates a new type by picking a set of properties from the original type:
interface Person {
name: string;
age: number;
address: string;
}
type PersonNameAge = Pick<Person, 'name' | 'age'>;
const personNameAge: PersonNameAge = { name: 'John Doe', age: 30 };
Omit<Type, Keys>
The Omit
utility type creates a new type by omitting a set of properties from the original type:
interface Person {
name: string;
age: number;
address: string;
}
type PersonWithoutAddress = Omit<Person, 'address'>;
const personWithoutAddress: PersonWithoutAddress = { name: 'John Doe', age: 30 };
Extract<Type, Union>
The Extract
utility type creates a new type by extracting the types that are assignable to the specified union from the original type:
type ActionTypes = 'add' | 'update' | 'delete';
type OtherActions = 'add' | 'search';
type CommonActions = Extract<ActionTypes, OtherActions>; // "add"
Exclude<Type, Union>
The Exclude
utility type creates a new type by excluding the types that are assignable to the specified union from the original type:
type ActionTypes = 'add' | 'update' | 'delete';
type OtherActions = 'add' | 'search';
type ExclusiveActions = Exclude<ActionTypes, OtherActions>; // "update" | "delete"
Conclusion
In this tutorial, we have explored utility types in TypeScript. Understanding how to use utility types effectively will enable you to create more flexible and type-safe code.