DEV Community

Cover image for The Power of TypeScript Utility Types ๐Ÿš€
Nilupul Perera
Nilupul Perera

Posted on

2

The Power of TypeScript Utility Types ๐Ÿš€

TypeScript provides a powerful set of utility types that enhance type safety, reduce redundancy, and improve code maintainability. These built-in utility types allow developers to transform, filter, and manipulate types effectively. Whether you're working with objects, unions, or function parameters, utility types can simplify complex type definitions.

In this post, weโ€™ll explore essential TypeScript utility types with real-world examples and best practices.


1๏ธโƒฃ Partial โ€“ Make All Properties Optional

Partial<T> creates a new type where all properties of T become optional. This is useful for updating objects without requiring all properties.

Example:

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

function updateUser(user: User, updates: Partial<User>): User {
  return { ...user, ...updates };
}

const user1: User = { id: 1, name: "Alice", email: "alice@example.com" };
const updatedUser = updateUser(user1, { name: "Bob" });

console.log(updatedUser); // { id: 1, name: "Bob", email: "alice@example.com" }
Enter fullscreen mode Exit fullscreen mode

2๏ธโƒฃ Readonly โ€“ Prevent Object Modification

Readonly<T> ensures that all properties of an object cannot be changed after initialization.

Example:

type Settings = {
  theme: string;
  darkMode: boolean;
};

const config: Readonly<Settings> = { theme: "light", darkMode: false };

// config.darkMode = true; // โŒ Error: Cannot assign to 'darkMode' because it is a read-only property.
Enter fullscreen mode Exit fullscreen mode

3๏ธโƒฃ Pick โ€“ Select Specific Properties

Pick<T, K> lets you extract a subset of properties from an existing type.

Example:

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

type UserPreview = Pick<User, "id" | "name">;

const userPreview: UserPreview = { id: 1, name: "Alice" };
// No 'email' property required
Enter fullscreen mode Exit fullscreen mode

4๏ธโƒฃ Omit โ€“ Exclude Specific Properties

Omit<T, K> is the opposite of Pick, allowing you to remove specific properties from a type.

Example:

type UserWithoutEmail = Omit<User, "email">;

const userWithoutEmail: UserWithoutEmail = { id: 1, name: "Alice" };
// No 'email' property allowed
Enter fullscreen mode Exit fullscreen mode

5๏ธโƒฃ Record โ€“ Create Mapped Types

Record<K, T> helps define objects where keys are of type K and values are of type T.

Example:

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

const userRoles: Record<Role, number> = {
  admin: 1,
  editor: 2,
  user: 3,
};
Enter fullscreen mode Exit fullscreen mode

6๏ธโƒฃ Exclude & Extract โ€“ Filter Union Types

  • Exclude<T, U> removes specific types from a union.
  • Extract<T, U> keeps only the matching types from a union.

Example:

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

type ActiveStatus = Exclude<Status, "error">; // "success" | "pending"
type ErrorStatus = Extract<Status, "error">; // "error"
Enter fullscreen mode Exit fullscreen mode

7๏ธโƒฃ NonNullable โ€“ Remove null and undefined

NonNullable<T> ensures a type doesnโ€™t contain null or undefined.

Example:

type Name = string | null | undefined;

type ValidName = NonNullable<Name>; // string
Enter fullscreen mode Exit fullscreen mode

๐Ÿš€ Conclusion

TypeScript utility types enhance code maintainability, reduce repetition, and improve type safety. Whether you need to make properties optional, readonly, or filter union types, these utilities are incredibly powerful.

By leveraging these built-in tools, you can write more efficient, error-free TypeScript code.

๐Ÿ’ก Which utility type do you use the most? Let me know in the comments! ๐Ÿ‘‡


๐Ÿ“Œ Stay tuned for the next post: Server Components vs. Server-Side Rendering in Next.js 15!

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

๐Ÿ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someoneโ€™s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay