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 ofT
optional. 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 ofT
required, the opposite ofPartial<T>
. -
Readonly<T>
: Makes all properties ofT
read-only, meaning their values cannot be changed once they're set. -
Record<K, T>
: Creates a type with a set of propertiesK
of a given typeT
.K
extendsstring | number | symbol
, making this utility type useful for dictionary objects with known keys. -
Pick<T, K>
: Constructs a type by picking the set of propertiesK
fromT
. 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 propertiesK
fromT
, essentially the opposite ofPick<T, K>
. -
Exclude<T, U>
: Constructs a type by excluding fromT
all properties that are assignable toU
. It's often used to remove certain types from a union. -
Extract<T, U>
: Constructs a type by extracting fromT
all properties that are assignable toU
, essentially the opposite ofExclude<T, U>
. -
NonNullable<T>
: Constructs a type by excludingnull
andundefined
fromT
. It's useful for ensuring a type doesn't includenull
orundefined
. -
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 thethis
parameter from a function type, orunknown
if the function type has nothis
parameter. -
OmitThisParameter<T>
: Removes thethis
parameter from the function typeT
and returns a new function type. -
ThisType<T>
: Marker utility that doesn't return a transformed type. It's used in the--noImplicitThis
flag for contextualthis
typing.
These utility types empower you to perform complex type manipulations succinctly and efficiently, making your TypeScript code more flexible and maintainable.