Creating Types from Types
Is it possible to create new types composing, manipulating or transforming existing types.
Intersection Types (&
):
Allow you to combine multiple types into a single type:
Union Types (|
):
Allow you to define a type that can be one of several types:
Mapped Types:
Allow you to transform the properties of an existing type to create new type:
Conditional types:
Allow you to create types based on some conditions:
Indexed Access Types
In TypeScript is it possible to access and manipulate the types of properties within another type using an index, Type[Key]
.
Utility Types
Several built-in utility types can be used to manipulate types, below a list of the most common used:
Awaited<T>
Constructs a type recursively unwrap Promises.
Partial<T>
Constructs a type with all properties of T set to optional.
Required<T>
Constructs a type with all properties of T set to required.
Readonly<T>
Constructs a type with all properties of T set to readonly.
Record<K, T>
Constructs a type with a set of properties K of type T.
Pick<T, K>
Constructs a type by picking the specified properties K from T.
Omit<T, K>
Constructs a type by omitting the specified properties K from T.
Exclude<T, U>
Constructs a type by excluding all values of type U from T.
Constructs a type by extracting all values of type U from T.
NonNullable<T>
Constructs a type by excluding null and undefined from T.
Parameters<T>
Extracts the parameter types of a function type T.
ConstructorParameters<T>
Extracts the parameter types of a constructor function type T.
ReturnType<T>
Extracts the return type of a function type T.
InstanceType<T>
Extracts the instance type of a class type T.
ThisParameterType<T>
Extracts the type of ‘this’ parameter from a function type T.
OmitThisParameter<T>
Removes the ‘this’ parameter from a function type T.
ThisType<T>
Servers as a market for a contextual this
type.
Uppercase<T>
Make uppercase the name of the input type T.
Lowercase<T>
Make lowercase the name of the input type T.
Capitalize<T>
Capitalize the name of the input type T.
Uncapitalize<T>
Uncapitalize the name of the input type T.
NoInfer<T>
NoInfer is a utility type designed to block the automatic inference of types within the scope of a generic function.
Example:
With NoInfer: