Objects 16 exercises
explainer

Making Type Properties Required in TypeScript

The Required type helper serves as an inverse to Partial.

Where Partial sets all elements as optional, Required makes all of the elements in the type required.

Here's an example type Coordinates where both x and y are optionally numbers:


type Coordinates = {
x?: number;
y?: n

Loading explainer

Transcript

00:00 The opposite type helper to partial is required. So instead of making a partial of a type, this makes all of the elements required. Super useful. So coordinates here, we can see that X and Y are both number or undefined and required after being applied to it, turns them into X number and Y number. So both required. And that's really, really nice.

00:21 You notice that this only works like one level deep. So if we have like A and B here where A is required, but B inside it is not required, you'll notice that B is still not required on there. So if you want to make like a deep required, then you'll have to look at a type helper library like Typefest to help you out.

00:40 But having them just on the top level makes it a bit more predictable and is still extremely useful in a bunch of situations.