In this tutorial, we will be exploring utility types in TypeScript, a robust set of tools that allow us to transform existing types in diverse ways, thereby enhancing our TypeScript code with more flexibility and power.
By the end of this tutorial, you will be able to:
- Understand the concept of utility types in TypeScript
- Know how to use utility types
- Apply utility types to transform existing types
Utility types in TypeScript are a set of generic types which can be used to represent transformations on types. They provide a way to create new types based on the existing ones.
Some commonly used utility types include:
- Partial<T>
- Readonly<T>
- Record<K,T>
- Pick<T,K>
When using utility types, keep in mind:
- Utility types can simplify your code and make it more readable.
- They are great tools for type manipulation, but they should not be overused. Use them where they make sense and simplify your code.
Partial<T>
type Car = {
model: string;
year: number;
};
type PartialCar = Partial<Car>;
let car1: PartialCar = { model: 'Toyota' }; // OK
let car2: PartialCar = { year: 2022 }; // OK
let car3: PartialCar = {}; // OK
In this example, Partial<T>
makes all properties in T
optional. This means that car1
, car2
, and car3
are all valid even though they don't have all the properties that Car
requires.
Readonly<T>
type Car = {
model: string;
year: number;
};
type ReadonlyCar = Readonly<Car>;
let car: ReadonlyCar = { model: 'Toyota', year: 2022 };
car.year = 2023; // Error: Cannot assign to 'year' because it is a read-only property.
Readonly<T>
makes all properties in T
read-only.
In this tutorial, we have learned about utility types in TypeScript and how we can use them to transform existing types. We have also explored some commonly used utility types with examples.
You can further explore utility types by visiting the official TypeScript documentation here.
Pick<T,K>
utility type to pick specific properties from a type.Record<K,T>
utility type to create a type with keys of K
and values of T
.type CarModelAndColor = Pick
let car: CarModelAndColor = { model: 'Toyota', color: 'Red' }; // OK
``
In this solution,
Pickis used to pick the 'model' and 'color' properties from
Car`.
let carColors: CarColors = {
Toyota: 'Red',
Honda: 'Blue',
BMW: 'Black'
}; // OK
``
In this solution,
Recordis used to create a type with keys of 'Toyota', 'Honda', 'BMW' and values of type
string`.
Try to use utility types in your own TypeScript projects or in coding problems to get a better understanding of how and when to use them.