DEV Community

Cover image for TypeScript Utility Types and How They Can Save Your Time
FredAbod
FredAbod

Posted on

3

TypeScript Utility Types and How They Can Save Your Time

TypeScript Utility Types and How They Can Save Your Time

What are TypeScript Utility Types

They are powerful tools that can make your code cleaner, more expressive, and less error-prone. If you’ve ever found yourself writing repetitive or complex type definitions, these built-in utilities can help simplify your work. This article will explore some of the most useful utility types and provide practical examples to show how they can save time and effort.

Let's Dive into It
Dive

Partial: Making All Properties Optional

The Partial utility type converts all properties in a given type to optional.

interface User {
  id: number;
  name: string;
  email: string;
}

// All properties are optional now
const updateUser = (user: Partial<User>) => {
  console.log(user);
};

updateUser({ name: "Alice" }); // Valid
Enter fullscreen mode Exit fullscreen mode

Use Case: Perfect for scenarios where you’re updating only a subset of an object’s fields.

Pick: Selecting Specific Keys

The Pick utility type lets you create a new type by selecting specific keys from an existing type.

interface User {
  id: number;
  name: string;
  email: string;
  isAdmin: boolean;
}

// Only id and name are included in the new type
type UserPreview = Pick<User, "id" | "name">;

const userPreview: UserPreview = {
  id: 1,
  name: "Bob",
};
Enter fullscreen mode Exit fullscreen mode

Use Case: Ideal for creating lightweight versions of an object.

Omit: Excluding Specific Keys

The Omit utility type creates a new type by excluding specific keys from an existing type.

interface User {
  id: number;
  name: string;
  email: string;
  isAdmin: boolean;
}

// Excludes email and isAdmin
type BasicUser = Omit<User, "email" | "isAdmin">;

const basicUser: BasicUser = {
  id: 2,
  name: "Charlie",
};
Enter fullscreen mode Exit fullscreen mode

Use Case: Useful when you need to expose only a subset of an object’s properties.

Readonly*: Making Properties Immutable*

The Readonly utility type makes all properties of a type immutable.

interface User {
  id: number;
  name: string;
}

const user: Readonly<User> = {
  id: 3,
  name: "Diana",
};

user.name = "Eve"; // Error: Cannot assign to 'name' because it is a read-only property
Enter fullscreen mode Exit fullscreen mode

Use case: Ensures that certain data cannot be modified after initialization.

Record: Defining Object Types

The Record utility type helps create a type with a fixed set of keys and values of a specific type.

// A record of roles mapped to user names
const userRoles: Record<string, string> = {
  admin: "Alice",
  editor: "Bob",
  viewer: "Charlie",
};

console.log(userRoles.editor); // "Bob"
Enter fullscreen mode Exit fullscreen mode

Use Case: Useful for creating maps or dictionaries.

ReturnType*: Extracting a Function’s Return Type*

The ReturnType utility type extracts the return type of a given function type.

function getUser() {
  return { id: 4, name: "Frank" };
}

type UserReturnType = ReturnType<typeof getUser>;

const user: UserReturnType = { id: 4, name: "Frank" };
Enter fullscreen mode Exit fullscreen mode

Use case: Helps ensure consistency when working with function return values.

Parameters*: Extracting Function Parameters*

The Parameters utility type extracts the parameter types of a given function type as a tuple.

function login(username: string, password: string): boolean {
  return username === "admin" && password === "password123";
}

type LoginParams = Parameters<typeof login>;

const credentials: LoginParams = ["admin", "password123"];
login(...credentials); // true
Enter fullscreen mode Exit fullscreen mode

Use case: Great for creating reusable parameter lists.

TypeScript’s utility types are an easy way to save time and write better code. Start using them in your projects today! If you enjoyed this article, share it with your network or leave a comment below. Let’s keep learning together!

Sign Out

Billboard image

The fastest way to detect downtimes

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitoring.

Get started now

Top comments (0)

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay