Start Coding

Topics

TypeScript Utility Types

TypeScript utility types are a powerful feature that enhances type manipulation and transformation. They provide a set of built-in types to help developers create more flexible and reusable code.

What are Utility Types?

Utility types in TypeScript are pre-defined generic types that perform common type transformations. They allow developers to modify existing types without creating new ones from scratch.

Common Utility Types

1. Partial<T>

The Partial<T> utility type makes all properties of a type optional.


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

type PartialUser = Partial<User>;
// Equivalent to: { name?: string; age?: number; }
    

2. Required<T>

Contrary to Partial<T>, Required<T> makes all properties required.


interface Config {
    debug?: boolean;
    timeout?: number;
}

type RequiredConfig = Required<Config>;
// Equivalent to: { debug: boolean; timeout: number; }
    

3. Pick<T, K>

The Pick<T, K> utility type creates a new type by selecting a set of properties from an existing type.


interface Person {
    name: string;
    age: number;
    address: string;
}

type NameAge = Pick<Person, 'name' | 'age'>;
// Equivalent to: { name: string; age: number; }
    

4. Omit<T, K>

Omit<T, K> creates a new type by removing specified properties from an existing type.


interface Product {
    id: number;
    name: string;
    price: number;
    description: string;
}

type ProductSummary = Omit<Product, 'description'>;
// Equivalent to: { id: number; name: string; price: number; }
    

Best Practices

  • Use utility types to avoid code duplication and improve maintainability.
  • Combine multiple utility types for complex type transformations.
  • Leverage utility types in Generics in TypeScript for more flexible functions and classes.
  • Consider creating custom utility types for project-specific needs.

Advanced Utility Types

TypeScript also provides more advanced utility types for complex scenarios:

  • Readonly<T>: Makes all properties of a type readonly.
  • Record<K, T>: Creates an object type with keys of type K and values of type T.
  • Exclude<T, U>: Excludes types in U from T.
  • Extract<T, U>: Extracts types in U from T.

Conclusion

Utility types are an essential part of TypeScript's type system. They provide a powerful way to manipulate and transform types, leading to more expressive and maintainable code. By mastering utility types, developers can write more robust and flexible TypeScript applications.

For more advanced type manipulations, explore Conditional Types and Mapped Types in TypeScript.