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:

Beginners Guide to TypeScript
Arindam Majumder ・ May 8 '24
and then come back to this one.
So, without delaying any further, Let's START!
5 Advanced TypeScript APIs
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>
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;
}
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'>;
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;
}
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>
-
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;
}
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>
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;
}
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>
-
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;
}
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',
};
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 theReadonly
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>
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';
And we want to exclude certain roles from specific operations. For that,we'll use Exclude Utility type :
type AllowedRoles = Exclude<UserRole, 'guest' | 'viewer'>;
In this case, AllowedRoles
is the newly created type which contains 'admin' and 'editor'. This is similar as the following:
type AllowedRoles = 'admin' | 'editor';
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>
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;
}
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>;
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>
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');
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 : )
Top comments (0)