Utility types in Typescript


2 min read

Cover Image for Utility types in Typescript

In this series we are going utility types in Typescript which are commonly used. This will help us to perform common transformation.

Below are the list of utility types we are going to cover in this series:

  • Record<KeyType, ValueType>

  • Partial<Type>

  • Required<Type>

  • Readonly<Type>

  • Pick<Type>

  • Omit<Type>

  • Exclude<Type>

  • Extract<Type>

  • Parameters<Type>

  • ReturnType<Type>

  • Promise<Type>

  • Awaited<Type>

  • String Transformation Type

    • Upper<Type>

    • Lower<Type>

    • Capitalize<Type>

    • Uncapitalize<Type>

Type Transformation

Before going into each utility type that is going to help us in performing day to day common transformation, we should first understand what exactly is Type Transformation.

Transformation utility is just helpers which is going to transform from one shape to another or in terms of type is changing from one type to another.

Why Type Transformation

Let's understand this using a simple example:

You have an array of string and you would like to calculate length of each word

const arr = ["Ultraviolete", "Samsung", "Apple", "Google"];
// expected outpu
// [ 12, 7, 5, 6]

This you can easily achieve this using for-loop as

const arr = ["Ultraviolete", "Samsung", "Apple", "Google"];;
let result = [];
for(let i = 0 ; i < arr.length; ++i) {
console.log(result); // [12, 7, 5, 6]

Above code works, But if you writing code for sometime then you might not be thinking about this solution. You might have thought of using Array.prototype.map which makes our code succinct, easy to understand, one-liner and easy to maintain. So you can get the same result as:

const arr = ["Ultraviolete", "Samsung", "Apple", "Google"];;
const result = arr.map(str => str.length);
console.log(result); // [12, 7, 5, 6]

More movable piece of code make your code hard to maintain - DECPK

There could be so many reason to go for Array.prototype.map to solve this problem. Some of them are:

  • It is succinct and easy to read.

  • Easy to maintain

  • You don't want to re-invent the wheel means you don't want to do what Javascript is by default giving us.

It is just utility method available on arrays given by Javascript to make our life easier.

In the same way, Typescript is also providing us bunch of utilities that can help us in type transformation and makes our life easier.

Let's learn Type Transformation in easy way 😊