TypeScript comes with a large number of predefined generic types that can help with some common type manipulation
Utility Types#
Utility types help to manipulate or create other new types from existing ones
Partial<Type>#
The Partial type takes in another Type
and produces a type where all of its properties are optional.
Consider we have the following interface:
If we want to create a type where all of its properties are optional:
This is equivalent to:
Required<Type>#
The opposite of Partial; The Required type takes in another Type
and produces a type where all of its properties are required.
Consider we have the following interface:
If we want to create a type where all of its properties are required:
This is equivalent to:
Readonly<Type>#
Create a new type where all properties of Type
are set to read-only, meaning the properties are immutable
Record<Keys, Type>#
This utility creates an object type with properties of specified Keys
and values of another specified Type
Pick<Type, Keys>#
Creates a new type by extracting a specified Keys
from Type
This is equivalent to:
Omit<Type, Keys>#
The opposite of Pick; creates a new type by excluding specified Keys
from the original Type
This is equivalent to:
Exclude<UnionType, ExcludedMembers>#
Creates a new type by excluding specified ExcludedMembers
from a given UnionType
.
This is equivalent to:
NonNullable<Type>#
Creates a new type by omitting null and undefined from Type
This is equivalent to:
Parameters<Type>#
Creates a new type by extracting the parameters Type
of a function
This is equivalent to:
Conclusion#
- Utility Types reduce redundancy and ensure the type stays up to date with the original type.