Sobes.tech
Middle

Tell me about utility types in TypeScript.

sobes.tech AI

Answer from AI

Utility types in TypeScript are built-in types that allow transforming existing data types into new types by performing various useful operations. They help increase flexibility and reusability of types, reducing code redundancy.

Main utility types:

  • Partial<Type>: Creates a new type where all properties of Type become optional.

    interface User {
      id: number;
      name: string;
      age: number;
    }
    
    type PartialUser = Partial<User>;
    // PartialUser will be { id?: number; name?: string; age?: number; }
    
  • Readonly<Type>: Creates a new type where all properties of Type are read-only.

    interface Point {
      x: number;
      y: number;
    }
    
    type ReadonlyPoint = Readonly<Point>;
    // ReadonlyPoint will be { readonly x: number; readonly y: number; }
    
  • Pick<Type, Keys>: Creates a type by selecting a set of properties Keys from Type.

    interface Product {
      id: number;
      name: string;
      price: number;
      description: string;
    }
    
    type ProductSummary = Pick<Product, 'id' | 'name' | 'price'>;
    // ProductSummary will be { id: number; name: string; price: number; }
    
  • Omit<Type, Keys>: Creates a type by excluding a set of properties Keys from Type.

    interface Order {
      id: number;
      productId: number;
      quantity: number;
      timestamp: string;
    }
    
    type OrderDetails = Omit<Order, 'timestamp'>;
    // OrderDetails will be { id: number; productId: number; quantity: number; }
    
  • Exclude<Type, ExcludedUnion>: Creates a type by excluding elements from Type that can be assigned to ExcludedUnion. Used for union types.

    type Colors = 'red' | 'green' | 'blue' | 'yellow';
    type PrimaryColors = Exclude<Colors, 'yellow'>;
    // PrimaryColors will be 'red' | 'green' | 'blue'
    
  • Extract<Type, Union>: Creates a type by selecting elements from Type that can be assigned to Union. Used for union types.

    type AllAnimals = 'dog' | 'cat' | 'fish' | 'bird';
    type PetAnimals = Extract<AllAnimals, 'dog' | 'cat'>;
    // PetAnimals will be 'dog' | 'cat'
    
  • NonNullable<Type>: Creates a type excluding null and undefined from Type.

    type MaybeString = string | null | undefined;
    type NotNullableString = NonNullable<MaybeString>;
    // NotNullableString will be string
    
  • Record<Keys, Type>: Creates a type for an object with keys from Keys and values of type Type.

    type CityPopulation = Record<string, number>;
    // CityPopulation will be { [key: string]: number }
    
    const population: CityPopulation = {
      "Moscow": 12635466,
      "Saint Petersburg": 5381033,
    };
    
  • Parameters<Type>: Returns a tuple of the parameter types of function Type.

    function greet(name: string, age: number): string {
      return `Hello, ${name}! You are ${age}.`;
    }
    
    type GreetParams = Parameters<typeof greet>;
    // GreetParams will be [string, number]
    
  • ReturnType<Type>: Returns the return type of function Type.

    function calculateSum(a: number, b: number): number {
      return a + b;
    }
    
    type SumResult = ReturnType<typeof calculateSum>;
    // SumResult will be number
    
  • ConstructorParameters<Type>: Returns a tuple or array of the constructor parameters of class Type.

    class MyClass {
      constructor(name: string, id: number) {}
    }
    
    type MyClassParams = ConstructorParameters<typeof MyClass>;
    // MyClassParams will be [string, number]
    
  • InstanceType<Type>: Returns the instance type of class Type.

    class AnotherClass {
      value: string;
      constructor(v: string) {
        this.value = v;
      }
    }
    
    type AnotherClassInstance = InstanceType<typeof AnotherClass>;
    // AnotherClassInstance will be AnotherClass
    

Using utility types makes code safer, more maintainable, and expressive, allowing effective management of complex data types.