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 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) => { console.log(user); }; updateUser({ name: "Alice" }); // Valid 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; const userPreview: UserPreview = { id: 1, name: "Bob", }; 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; const basicUser: BasicUser = { id: 2, name: "Charlie", }; 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 = { id: 3, name: "Diana", }; user.name = "Eve"; // Error: Cannot assign to 'name' because it is a read-only property 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 = { admin: "Alice", editor: "Bob", viewer: "Charlie", }; console.log(userRoles.editor); // "Bob" 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; const user: UserReturnType = { id: 4, name: "Frank" }; 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; const credentials: LoginParams = ["admin", "password123"]; login(...credentials); // true 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!

Jan 23, 2025 - 16:53
 0
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

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

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

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

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"

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

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

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

What's Your Reaction?

like

dislike

love

funny

angry

sad

wow