Skip to main content

Utility Types

TypeScript provides several utility types to facilitate common type transformations, which can help you manipulate types in a more flexible and reusable way. These utilities are part of the TypeScript standard library and can significantly reduce the amount of type boilerplate code you need to write. Here's a list of some of the most commonly used TypeScript utility types:

  1. Partial<T>: Makes all properties of T optional. This utility is helpful when you want to create a type similar to another but with all its properties as optional.

  2. Required<T>: Makes all properties of T required, the opposite of Partial<T>.

  3. Readonly<T>: Makes all properties of T read-only, meaning their values cannot be changed once they're set.

  4. Record<K, T>: Creates a type with a set of properties K of a given type T. K extends string | number | symbol, making this utility type useful for dictionary objects with known keys.

  5. Pick<T, K>: Constructs a type by picking the set of properties K from T. It's useful for creating new types that only include a subset of properties from another type.

  6. Omit<T, K>: Constructs a type by omitting the set of properties K from T, essentially the opposite of Pick<T, K>.

  7. Exclude<T, U>: Constructs a type by excluding from T all properties that are assignable to U. It's often used to remove certain types from a union.

  8. Extract<T, U>: Constructs a type by extracting from T all properties that are assignable to U, essentially the opposite of Exclude<T, U>.

  9. NonNullable<T>: Constructs a type by excluding null and undefined from T. It's useful for ensuring a type doesn't include null or undefined.

  10. Parameters<T>: Constructs a tuple type of the types of the parameters of a function type T.

  11. ReturnType<T>: Constructs a type consisting of the return type of a function type T.

  12. InstanceType<T>: Constructs a type consisting of the instance type of a constructor function type T.

  13. ThisParameterType<T>: Extracts the type of the this parameter from a function type, or unknown if the function type has no this parameter.

  14. OmitThisParameter<T>: Removes the this parameter from the function type T and returns a new function type.

  15. ThisType<T>: Marker utility that doesn't return a transformed type. It's used in the --noImplicitThis flag for contextual this typing.

These utility types empower you to perform complex type manipulations succinctly and efficiently, making your TypeScript code more flexible and maintainable.