Home > Web Front-end > JS Tutorial > Unleashing the Power of Utility Types in TypeScript

Unleashing the Power of Utility Types in TypeScript

Patricia Arquette
Release: 2024-11-11 18:44:03
Original
249 people have browsed it

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

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!

Copy after login
Copy after login

Required

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!
Copy after login
Copy after login

Record

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"],
};
Copy after login
Copy after login

Pick

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">;
Copy after login

Omit

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;
};

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!

Copy after login
Copy after login

Exclude

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 UserWithOptionalFields = {
  id: number;
  name?: string;
  email?: string;
};

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

Extract

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 Role = "admin" | "user" | "guest";

const rolePermissions: Record<Role, string[]> = {
  admin: ["read", "write", "delete"],
  user: ["read", "write"],
  guest: ["read"],
};
Copy after login
Copy after login

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! ?

The above is the detailed content of Unleashing the Power of Utility Types in TypeScript. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template