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:
-
Partial<T>: Makes all properties ofToptional. This utility is helpful when you want to create a type similar to another but with all its properties as optional. -
Required<T>: Makes all properties ofTrequired, the opposite ofPartial<T>. -
Readonly<T>: Makes all properties ofTread-only, meaning their values cannot be changed once they're set. -
Record<K, T>: Creates a type with a set of propertiesKof a given typeT.Kextendsstring | number | symbol, making this utility type useful for dictionary objects with known keys. -
Pick<T, K>: Constructs a type by picking the set of propertiesKfromT. It's useful for creating new types that only include a subset of properties from another type. -
Omit<T, K>: Constructs a type by omitting the set of propertiesKfromT, essentially the opposite ofPick<T, K>. -
Exclude<T, U>: Constructs a type by excluding fromTall properties that are assignable toU. It's often used to remove certain types from a union. -
Extract<T, U>: Constructs a type by extracting fromTall properties that are assignable toU, essentially the opposite ofExclude<T, U>. -
NonNullable<T>: Constructs a type by excludingnullandundefinedfromT. It's useful for ensuring a type doesn't includenullorundefined. -
Parameters<T>: Constructs a tuple type of the types of the parameters of a function typeT. -
ReturnType<T>: Constructs a type consisting of the return type of a function typeT. -
InstanceType<T>: Constructs a type consisting of the instance type of a constructor function typeT. -
ThisParameterType<T>: Extracts the type of thethisparameter from a function type, orunknownif the function type has nothisparameter. -
OmitThisParameter<T>: Removes thethisparameter from the function typeTand returns a new function type. -
ThisType<T>: Marker utility that doesn't return a transformed type. It's used in the--noImplicitThisflag for contextualthistyping.
These utility types empower you to perform complex type manipulations succinctly and efficiently, making your TypeScript code more flexible and maintainable.