Skip to content
DeveloperMemos

Using Optionals in TypeScript

TypeScript, Optionals1 min read

In TypeScript, optionals provide a way to handle nullable values and help prevent unexpected runtime errors. Optionals allow you to indicate that a value may be present or absent. This flexibility is particularly useful when dealing with variables or properties that can have undefined or null values. In this article, we will explore how to utilize optionals in TypeScript and understand their benefits.

Declaring Optionals

To declare an optional variable or property in TypeScript, you can use the union type syntax by appending a question mark (?) to the type. For example:

1let username: string | undefined;
2let phoneNumber: number | undefined;
3
4class Person {
5 name: string;
6 age?: number;
7
8 constructor(name: string, age?: number) {
9 this.name = name;
10 this.age = age;
11 }
12}

In the above code snippet, age is declared as an optional property using the question mark. This means the age property can either have a number value or be undefined.

Checking for Undefined or Null

When working with optionals, it is important to check whether a value is defined or not before using it. You can do this using conditional statements, such as if statements or the nullish coalescing operator (??). Here's an example:

1function printAge(person: Person): void {
2 if (person.age !== undefined) {
3 console.log(`The person's age is ${person.age}`);
4 } else {
5 console.log(`The person's age is unknown`);
6 }
7}
8
9const john: Person = new Person("John Doe", 30);
10printAge(john); // Output: The person's age is 30
11
12const jane: Person = new Person("Jane Smith");
13printAge(jane); // Output: The person's age is unknown

In the above code, the printAge function checks if the age property of the Person object is defined before printing it. If the age is undefined, it prints "unknown" instead.

Alternatively, you can use the nullish coalescing operator (??) to provide a default value in case the optional property is undefined:

1function printAge(person: Person): void {
2 const age = person.age ?? "unknown";
3 console.log(`The person's age is ${age}`);
4}

Using Optional Chaining

TypeScript introduced the optional chaining operator (?.) to simplify working with nested optionals. It allows you to access properties or call methods on an optional value without explicitly checking if it is defined. If any part of the chain is undefined, the expression returns undefined. Here's an example:

1const user = {
2 name: "John Doe",
3 address: {
4 city: "New York",
5 street: "123 Main St",
6 },
7};
8
9console.log(user.address?.city); // Output: New York
10console.log(user.address?.zipCode); // Output: undefined

In the above code, the optional chaining operator ensures that accessing user.address.city and user.address.zipCode does not throw an error even if address or city is undefined.

Conclusion

Remember to always check for undefined values before performing operations on optionals to ensure your code behaves as expected. Optionals are a valuable tool in TypeScript's type system that can greatly enhance your development experience!