DEV Community

Cover image for Unleashing the Power of Utility Types in TypeScript
Ashutosh Kumar
Ashutosh Kumar

Posted on

Unleashing the Power of Utility Types in TypeScript

Hey there, TypeScript warrior! 💪 So, you’re knee-deep in TypeScript, and maybe you’ve wondered, "Why is there so much code just for managing types?" Don’t worry—you’re not alone. We’re all on this wild, statically-typed ride together.

Today, we’re diving into some of TypeScript’s coolest tools, Utility Types. These are like those little cheat codes in a video game that help you speed up and simplify your code. So, let’s roll up our sleeves and take a fun tour of the most useful utility types in TypeScript—and how they can make your code way less of a headache.

Whaaat? More types.

Imagine you’re trying to work with TypeScript types without writing everything from scratch (because who’s got time for that?). Utility types let you create new types by transforming or reusing parts of other types. Think of them as those fancy kitchen gadgets that slice and dice without needing any extra effort. They save time, reduce redundancy, and make your code a whole lot easier to manage. Let’s break them down one by one!

Partial<Type>

What It Does: Makes all the properties in a type optional. Yeah, it’s that easy.

Why You’ll Love It: Perfect for those times when you need some of an object, but not all of it.

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

function updateUser(id: number, newValues: Partial<User>) {
  // Update only the properties you need, no need to bring everything.
}

updateUser(1, { name: "Ash" }); // Only updating name, thanks to Partial!

Enter fullscreen mode Exit fullscreen mode

Required<Type>

What It Does: Makes all properties in a type mandatory. TypeScript’s little way of saying, “No skipping any fields!”

Why You’ll Love It: Sometimes, optional just isn’t an option. You need everything locked and loaded, especially if certain properties were optional before.

type UserWithOptionalFields = {
  id: number;
  name?: string;
  email?: string;
};

const user: Required<UserWithOptionalFields> = {
  id: 1,
  name: "John",
  email: "john@example.com",
}; // All properties are now required!
Enter fullscreen mode Exit fullscreen mode

Record<Keys, Type>

What It Does: Creates an object type with the keys Keys and values Type. Think of it as TypeScript’s “create your own dictionary” feature.

Why You’ll Love It: This type is your best friend when you want a quick-and-easy way to map out data, especially if you know the keys ahead of time.

type Role = "admin" | "user" | "guest";

const rolePermissions: Record<Role, string[]> = {
  admin: ["read", "write", "delete"],
  user: ["read", "write"],
  guest: ["read"],
};
Enter fullscreen mode Exit fullscreen mode

Pick<Type, Keys>

What It Does: Takes an existing type and picks only the properties you specify. Think of it as TypeScript’s way of saying, “Let’s keep this short and sweet.”

Why You’ll Love It: Perfect for creating subsets of an existing type without dragging everything along, and cause it is one of my favourites.

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

type UserPreview = Pick<User, "id" | "name">;
Enter fullscreen mode Exit fullscreen mode

Omit<Type, Keys>

What It Does: It’s the opposite of Pick. It lets you exclude specific properties from a type.

Why You’ll Love It: Great when you have a type, but there’s just one pesky field you don’t want.

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

type PublicUser = Omit<User, "password">;
Enter fullscreen mode Exit fullscreen mode

Exclude<Type, ExcludedUnion>

What It Does: Removes certain types from a union. It’s the “kick out of the group chat” of TypeScript.

Why You’ll Love It: It’s super useful when you’ve got a big union but only need to handle some cases.

type Status = "success" | "error" | "loading";

type NonLoadingStatus = Exclude<Status, "loading">;
Enter fullscreen mode Exit fullscreen mode

Extract<Type, Union>

What It Does: The twin sibling of Exclude, Extract keeps only the types that match a given union.

Why You’ll Love It: This type narrows down a union type to only relevant pieces.

type Status = "success" | "error" | "loading";

type LoadingStatus = Extract<Status, "loading">; // Just "loading"
Enter fullscreen mode Exit fullscreen mode

And there you have it! 🎉 While Extract and Pickmay sound alike, they’re uniquely suited for different jobs: Extractis your filter for union types, while Picklets you cherry-pick properties from object types. The same goes for their counterparts, Excludeand Omit.

These utility types are small but mighty! They save time, reduce code redundancy, and keep things tidy. So next time you’re wrestling with types, remember these helpers. They’ll be there to simplify your TypeScript journey and make it a little more fun. Happy coding, and may your types always be exactly what you need! 🚀

Top comments (0)