DEV Community

Cover image for Typescript utility types that you must know

Typescript utility types that you must know

Arafat on April 02, 2023

Hello everyone, Today, In this article, we will go through some beneficial and essential utility types in Typescript that can make your life easier...
Collapse
 
gautamvaishnav profile image
Gautam Vaishnav

You are a great developer surly

Collapse
 
arafat4693 profile image
Arafat

Thanks for your nice comment😊.

Collapse
 
hexram profile image
Héctor Ramírez

Concise and to the point. I foresee a terrific developer in you...

Collapse
 
shu2210 profile image
s_yasunaga

Great post!
May I translate this article into Japanese and post it to community? (I'll definitely link this)

Collapse
 
arafat4693 profile image
Arafat

Sure, Go ahead!!!

Collapse
 
bybydev profile image
byby

Hot take: don't use any TS utility types :v

Collapse
 
voxpelli profile image
Pelle Wessman

Why? What would be the reason to avoid them?

Collapse
 
bybydev profile image
byby

Over using utility types may lead to code that is difficult to understand and maintain. Especially nesting many types together. I know this is a soft opinion, the point is I saw many projects with very complex type definitions. Here's an example:

type User = {
  id: number;
  name: string;
  email: string;
};

type VeryComplexUser = Readonly<Pick<User, "id">> &
  Partial<Omit<User, "email">> &
  { email: User["email"] | null } &
  { role: string } &
  Record<"email", string> & {
    role: User["name"] extends "admin" ? "admin" : "user";
  } & {
    name: User["name"];
  } & {
    id: { [K in keyof User["id"]]: User["id"][K] };
  } & {
    email: User["email"] & string;
  } & {
    role: Exclude<User["role"], "guest">;
  };
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
voxpelli profile image
Pelle Wessman

I think the main problem here is the overuse of intersections, something that can also be a performance issue.

Collapse
 
voxpelli profile image
Pelle Wessman

And when the built in utility types are not enough, then there’s the type-fest module with a ton more ones: github.com/sindresorhus/type-fest

Collapse
 
abhidadhaniya23 profile image
Abhi Dadhaniya

Thanks for this article, very easy to understand 😊

Collapse
 
jannisdev profile image
Jannis

Awesome post! Very helpful and those utility types are just awesome! 🔥

Collapse
 
salonidobhal13 profile image
Saloni Dobhal

Really good and helpful..!!

Collapse
 
abdultech profile image
AbdulTech

Really good and explanatory