DEV Community

Cover image for ⚡️5 Advanced TypeScript APIs You should know 🚀
Arindam Majumder
Arindam Majumder Subscriber

Posted on

2 1 1 1 1

⚡️5 Advanced TypeScript APIs You should know 🚀

Introduction

TypeScript has transformed the way we write JavaScript by providing a static type system that helps developers catch errors early and write more robust code.

But we often don't use typescript to it's full potential. It's much more than defining simple types and interfaces.

In this Article, we'll discuss 5 advance typescript APIs that will improve the way we write typescript code. If you're new to TypeScript, I suggest you read this article first:

and then come back to this one.

So, without delaying any further, Let's START!

GIF


5 Advanced TypeScript APIs

Getting Started with TypeScript in React: A Comprehensive Guide

Pick:

The Pick utility type in TypeScript is a powerful feature that allows us to construct new types by selecting a subset of properties from an existing type.

This is super useful when we need a certain field from complex data. It helps to improve readability and enhances type safety.

The Syntax of Pick is:

Pick<Type, Keys>
Enter fullscreen mode Exit fullscreen mode
  • Type: This is the original type where we'll take properties from.

  • Keys: The Properties we want to take from the Type. (Keys are separated by | )

Let's Understand it's usecase with an Example:

Suppose, We have a BlogData type in our application which looks like this:

type BlogData = {
  title: "string;"
  description: "string;"
  author: string;
  datePublished: string;
  summary: string;
  image?: string;
}
Enter fullscreen mode Exit fullscreen mode

And While Showing the Blog Card we only need the title, author and datePublished properties. For that, we can create a new type BlogCardData with Pick that only includes our required properties:

type BlogCardData = Pick<BlogData, 'title' | 'author' | 'datePublished'>;
Enter fullscreen mode Exit fullscreen mode

Here, BlogCardData is a new data type that contains only the title, author and datePublished properties. It's Similar to the following type:

type BlogCardData = {
  title: "string;"
  author: string;
  datePublished: string;
}
Enter fullscreen mode Exit fullscreen mode

Overall, Pick allows us to be explicit about what properties a function or component expects, leading to more maintainable and error-resistant code.


Partial

The Partial utility type in TypeScript is used to create a new type by making all properties of an existing type optional. This is particularly useful when we want to update a subset of an object's properties without proving the entire object.

The Syntax of Partial is:

Partial<Type>
Enter fullscreen mode Exit fullscreen mode
  • Type: It's the orginal which from which we'll create a new type making all the properties optional.

Let's Understand this With an example:

Take the same type BlogData that we have shown before.

type BlogData = {
  title: string;
  description: string;
  author: string;
  datePublished: string;
  summary: string;
  image: string;
}
Enter fullscreen mode Exit fullscreen mode

Now, we'll make the summary , image and description properties optional. To achieve that we'll use both Pick and Partial like the following:

// create a new type with the required properties with pick
type BlogPickData = Pick<Type, 'description' | 'summary' | 'image' >

// Make all the properties of BlogPickData as Optional
type BlogOptionalData = Partial<BlogPickData>
Enter fullscreen mode Exit fullscreen mode

Here, we have first created a new Data type BlogPickData with the properties we want to make optional and then created the BlogOptionalData type using partialto make those properties optional.

The BlogOptionalData type works similarly as this:

type BlogOptionalData = {
    description: string;
    summary: string;
    image: string;
}
Enter fullscreen mode Exit fullscreen mode

Overall, Partial allows us to create types that are more flexible for update operations while still maintaining type safety.


Readonly

As the name suggests, the Readonly utility type makes all properties of a given type read-only. That means when we create an object with this type, we can't reassign them.

This is very useful while writing configuration objects, constants or any sensitive data that we don't want to change later(to avoid mistakes).

The Syntax of Readonly is:

Readonly<Type>
Enter fullscreen mode Exit fullscreen mode
  • Type: It's the orginal type that we want to convert all the properties to read-only.

Let's understand this with an example:

Suppose, we have a config type for the configuration settings for an application:

type Config {
  endpoint: string;
  apiKey: string;
}
Enter fullscreen mode Exit fullscreen mode

Now we'll use the Readonly utility type to make the object read-only.

const config: Readonly<Config> = {
  endpoint: '<https://api.example.com>',
  apiKey: 'arindam_1729',
};
Enter fullscreen mode Exit fullscreen mode

It will ensure that a Config object cannot be modified after it's created. Now, if we attempt to modify the object, it will result in a TypeScript error.

Note: The Readonly utility type ensures that properties can't be changed, but only at the TypeScript level. This means it's a feature that works during compile-time. JavaScript, which is what TypeScript compiles into, doesn't have built-in immutability, so the Readonly rule doesn't apply at runtime.

Overall, it helps maintain the integrity of objects that represent fixed configurations or constants.


Exclude

The Exclude utility type is used to construct a type by excluding from a union type certain members that should not be allowed. This is very useful when we want to create a type that is a subset of another type, with some elements removed.

The syntax of Exclude is :

Exclude<T, U>
Enter fullscreen mode Exit fullscreen mode
  • T: This is the original type from which we'll exclude properties from.

  • U: The Properties we want to exclude from the union type.

Let's understand this with an example:

Suppose we have a application where we need to manage a list of user roles in an application:

type UserRole = 'admin' | 'editor' | 'viewer' | 'guest';
Enter fullscreen mode Exit fullscreen mode

And we want to exclude certain roles from specific operations. For that,we'll use Exclude Utility type :

type AllowedRoles = Exclude<UserRole, 'guest' | 'viewer'>;
Enter fullscreen mode Exit fullscreen mode

In this case, AllowedRoles is the newly created type which contains 'admin' and 'editor'. This is similar as the following:

 type AllowedRoles = 'admin' | 'editor';
Enter fullscreen mode Exit fullscreen mode

Overall, Exclude allows us to refine type definitions for specific use cases, enhancing type safety and clarity in your code.


Record & Map

The Record utility type and the Map object in TypeScript offer two powerful ways to work with collections of key-value pairs.

The Record utility type is used to construct a type with a set of properties K of a given type T.

The Syntax pf Record is :

Record<K,T>
Enter fullscreen mode Exit fullscreen mode
  • K: The set of the properties (keys).

  • T: The type of the properties (values).

Let's understand this with an example:

Suppose, we're building an application that manages a list of users of type User as following:

type User {
  id: string;
  name: string;
}
Enter fullscreen mode Exit fullscreen mode

Now, we'll use Record type to define the Users type:


// Using Record to type an object with string keys and User values
type Users = Record<string, User>;
Enter fullscreen mode Exit fullscreen mode

Here, Record creates a type where the keys are strings and the values are of type User.

On the other hand, The Map object in TypeScript (inherited from JavaScript) is a collection of key-value pairs where both the keys and values can be of any type.

The Syntax of Map is:

Map<keyType, valueType>
Enter fullscreen mode Exit fullscreen mode
  • keyType: The type of keys in the map (e.g., string, number).

  • valueType: The type of values in the map.

In the previous example, we can implement that using Map:

type User {
  id: string;
  name: string;
}

// Initialize an empty Map with string keys and User values
const usersMap = new Map<string, User>();

// Adding a user to the map
usersMap.set('user1', { id: '1', name: 'Arindam' });

// Retrieving a user from the map
const user = usersMap.get('user1');
Enter fullscreen mode Exit fullscreen mode

The Map provides methods like .set to add key-value pairs and .get to retrieve values by key.

Overall, Both Record and Map enhance TypeScript's ability to work with collections of data in a type-safe manner.


Conclusion

If you found this blog post helpful, please consider sharing it with others who might benefit. You can also follow me for more content on Javascript, React, and other web Development topics.

For Paid collaboration mail me at : arindammajumder2020@gmail.com

Connect with me on Twitter, LinkedIn, Youtube and GitHub.

Thank you for Reading : )

Thank You

Image of Quadratic

Free AI chart generator

Upload data, describe your vision, and get Python-powered, AI-generated charts instantly.

Try Quadratic free

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

DEV is better (more customized, reading settings like dark mode etc) when you're signed in!

Okay