JS Learning

Utility Types

Advanced TypeScriptSection 2 of 4advanced

Topic Overview

Take your time to understand each concept. Practice with the examples below!

Utility types are TypeScript's built-in helpers that transform existing types into new ones. They're like power tools for type manipulation - saving you time and making complex transformations simple!

What are Utility Types? Utility types are pre-built generic types that perform common type transformations. Instead of writing complex type logic yourself, you can use these ready-made solutions.

Essential Utility Types:

Partial<T> - Make Everything Optional:

  • Converts all properties to optional
  • Perfect for update operations
  • Example:Partial<User> for updating user profiles

Required<T> - Make Everything Required:

  • Opposite of Partial
  • Removes optional markers (?)
  • Useful for validation scenarios

Pick<T, K> - Cherry-Pick Properties:

  • Select specific properties from a type
  • Like choosing items from a menu
  • Example:Pick<User, 'id' | 'name'>

Omit<T, K> - Remove Properties:

  • Exclude specific properties
  • Great for creating subsets
  • Example:Omit<User, 'password'>

Record<K, T> - Dynamic Object Types:

  • Create object types with specific keys
  • All keys have the same value type
  • Example:Record<string, number> for scores

More Utility Types:

  • Readonly<T>:Make all properties readonly
  • ReadonlyArray<T>:Immutable arrays
  • ReturnType<T>:Get function return type
  • Parameters<T>:Get function parameter types
  • Exclude<T, U>:Remove types from unions
  • Extract<T, U>:Keep only matching types
  • NonNullable<T>:Remove null and undefined

Real-World Use Cases:

  • API responses:Partial for PATCH requests
  • Form handling:Pick for form subsets
  • State management:Readonly for immutable state
  • Configuration:Required for mandatory settings
  • Permissions:Record for role mappings

Combining Utility Types:

You can chain utility types for complex transformations:

  • Partial<Pick<User, 'name' | 'email'>>
  • Readonly<Required<Config>>
  • Record<string, Partial<User>>

Example

// Base interface
interface User {
id: number;
name: string;
email: string;
age: number;
isActive: boolean;
}
// Partial - makes all properties optional
type PartialUser = Partial<User>;
const updateUser: PartialUser = {
name: "John Doe" // Only updating name
};
// Required - makes all properties required
type RequiredUser = Required<User>;
// Pick - select specific properties
type UserProfile = Pick<User, 'id' | 'name' | 'email'>;
const profile: UserProfile = {
id: 1,
name: "Alice",
email: "alice@example.com"
};
// Omit - exclude specific properties
type UserWithoutId = Omit<User, 'id'>;
const newUser: UserWithoutId = {
name: "Bob",
email: "bob@example.com",
age: 25,
isActive: true
};
// Record - create object type with specific keys
type UserRoles = Record<string, boolean>;
const permissions: UserRoles = {
read: true,
write: false,
delete: false
};