Part of Series: TypeScript Utility Types
Typescript

How the TypeScript Required Type Works

Sponsor

In TypeScript, we sometimes need to enforce that an object has required properties, even if the original type defined some of them as optional. For that, TypeScript has a utility type called Required. Let's look at how it works.

TypeScript Required Utility Type

By default, if we define a new type in TypeScript, all fields within that type are automatically required:

type User = { firstName: string, lastName: string } let firstUser:User = { firstName: "John" }

Above, firstUser is of type User, but it's missing lastName. As such, this code returns an error:


Property 'lastName' is missing in type '{ firstName: string; }' but required in type 'User'.

If we expect a field to be optional, we can add a question mark to the end of it in our type definition. Below, we make lastName optional by writing lastName? instead:

type User = { firstName: string, lastName?: string } let firstUser:User = { firstName: "John" }

As such, this code does not throw an error - lastName is optional, so the fact that firstUser doesn't contain it is fine.

Forcing optional types to be required in TypeScript

Sometimes, we have a situation where most of the time, lastName is optional, but in some circumstances we require it to do something. In these cases, we can use the utility type Required. For example, if we want lastName to be required, even if it was originally defined as optional, we can write the following:

type User = { firstName: string, lastName?: string } let firstUser:User = { firstName: "John", } let secondUser:Required<User> = { firstName: "John" }

In this example, secondUser throws an error:


Property 'lastName' is missing in type '{ firstName: string; }' but required in type 'Required<User>'

So since we've used Required, we have to add lastName to avoid the error:

type User = { firstName: string, lastName?: string } let secondUser:Required<User> = { firstName: "John", lastName: "Doe" }

This can give us more flexibility, while allowing us to enforce field requirements for certain functionality in an application. As with other utility types, Required is meant to work with an interface or object type, like the User type we defined above. As such, it doesn't work with variables. This doesn't matter much, though, since a variable cannot have an empty value anyway.

Last Updated Wednesday, 6 April 2022
Part of Series: TypeScript Utility Types
Johnny Simpson
Johnny Simpson

More Tips and Tricks Typescript

Subscribe for Weekly Dev Tips

Subscribe to our weekly newsletter, to stay up to date with our latest web development and software engineering posts via email. You can opt out at any time.

Not a valid email