One minute
TypeScript: Required
As I am working a lot with TypeScript these days I ran into some interesting TypeScript Utility types that I would like to explore a bit more in a series of small blog posts.
Required<Type>
The Requred utility type is used to enforce that all keys of a type with some or all optional keys are required. So all keys should have a value when a object of this requred type is created.
example:
type Pizza = {
name: string,
spiciness?: number,
price?: number
}
The spiciness and price keys are defined as optional, with the Required utility type we can create a new type as Pizza but with all keys required:
type StrictPizza = Required<Pizza>;
Creating an object of this type could look something like:
const pizza: StrictPizza = {
name: 'Quatro Stagioni',
spiciness: 2,
price: 14.99
}
We have to provide values for all the keys.
For a complete overview of TypeScript Utility types please check: