Optional Properties In TypeScript

Optional Properties are those properties that are not mandatory. In the example below the person object name is usually mandatory but age may not be. When we create a person object without assigning a value to age the compiler throws age is missing in a type error. To solve this problem, we need to mark the property as optional.

Creating Optional Properties in TypeScript

To make a specific property optional just add a question mark (?) after the property name

Objects

Type Alias

Interface

Class

Note that we did not include age in the class constructor function. If you want to include that then make sure you mark it as an optional parameter

Optional Property and Undefined

Adding ? makes age as optional property. Trying to access the value of age returns undefined as expected.

But typescript also allows us to assign undefined value to an optional property although age is of type number.

This is because TypeScript treats every optional property as a union type of undefined and assigned type.

ExactOptionalPropertyTypes Config Option

In the previous section, we showed you that typescript allows us to assign undefined to an optional property.

You can stop that by setting the exactOptionalPropertyTypes to true in the tsconfig.json file under the section compilerOptions. Note that you also need to enable strictNullChecks for the exactOptionalPropertyTypes to work.

With exactOptionalPropertyTypes enabled, the TypeScript compiler throws an error when we try to assign the undefined to the age variable.

You can override the behavior by explicitly setting the type as undefined

Make all properties optional of an existing type

Typescript utility types allow us to construct a new type from an existing type. The Partial utility type is one such utility that takes a type and constructs a new type with all the properties set to optional.

The following is the syntax for converting an existing type to optional.

In this example, the Person interface has all properties marked as required. Assigning it an empty object will result in an error.

You can use the Partial<Person> to create a new type with all properties set to optional. Hence it will not result in any compiler error.

The following is one of the use cases for the Partial utility type.

The updatePerson function updates the subset of the properties of person object. The second argument to fields: Partial<Person> create fields object with a type of Person interface with all properties set to optional. This allows us to pass any combination arguments to updatePerson. It also provides a strong type of checking as we cannot pass a non-existing property.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top