TypeScript's Optional Chaining, Nullish Coalescing, and Null Assertion: What You Need to Know

TypeScript's Optional Chaining, Nullish Coalescing, and Null Assertion: What You Need to Know

null and undefined are primitive data types in TypeScript and there are some basic concepts related to their handling, namely Optional Chaining, Nullish Coalescing, and Null Assertion. Let's look into these topics one by one and understand them with the help of the required examples.

Optional Chaining

It is originally a JavaScript feature that works well with TypeScript's null handling too. It was released with ECMAScript 2020. This feature allows us to safely navigate through nested properties and methods of objects, without worrying about potentially undefined or null types. Optional Chaining operator is denoted by ?..

Let's understand through an example:

const student = {
    name: "Swapnil",
    examRecord: {
        testOneGiven: {
            response: "No",
            marks: 19
        }
}
}
console.log(student.examRecord.testTwoGiven) //this would work fine, but the result would be undefined as there is no record for second test

console.log(student.examRecord.testTwoGiven.marks) //now this will throw error as at first testTwoGiven doesn't exist and we are trying to fetch its marks, but this can be fixed using Optional Chaining operator

console.log(student.examRecord.testTwoGiven?.marks)// This will work and print undefined

Here, we have an object called student that stores the marks of the student in all the tests. But, here we don't have a record of test two and we are trying to fetch its marks, thus throwing an error. In cases like these, where we are not sure about existence of a variable/key in hierarchy, we can simply use ?. operator to avoid any kind of runtime error. In the above code, we can do:

console.log(student.examRecord.testTwoGiven?.marks)

This code won't throw any error at runtime, even though the answer would be NaN.


Nullish Coalescing

Nullish Coalescing is another JavaScript concept, that works well with TypeScript's null handling too. The Nullish Coalescing operator ?? provides a way to specify a fallback value for cases where the operand is null or undefined.

Let's understand through an example:

const name = null
console.log(name??'Anonymous')

Here, we have a variable name, that is null. In cases like these, we can use ?? operator, which would print Anonymous, rather than null. This works the same if the initial value of name is undefined too.

const name = undefined
console.log(name??'Anonymous')

But, lots of people think that ?? operator would always print the value that is written after it. That's not always the case. Let's see another example:

const name = 'Swapnil'
console.log(name??'Anonymous')

In this case Swapnil would be printed to console, not Anonymous. It' s because Swapnil is not null or undefined. It's a legit value and what ?? operator does is that if the initial value of the variable is null, then print the value provided after the ?? operator. But, here the initial value is not null or undefined, so it's printed as such.


Null Assertion

Null Assertion is a feature in TypeScript that allows developers to tell the compiler that a value is not null or undefined, even if the type system doesn't guarantee it. The operator that is used to do the same is !.

Let's understand through an example:

function greet(name: string | null) {
  console.log(`Hello, ${name!.toUpperCase()}!`); //! operator prevents any kind of compile-time error, but we will get an error at run time, if the value passed to this function is null
}

greet(null); // compiles successfully, but throws a runtime error
greet('Swapnil`); // compiles and logs "Hello, SWAPNIL!"

The problem here is that we are trying to convert null to upper case, but we won't get any error until runtime, as we are using ! operator.

Note: The null assertion operator is risky since the programmer is claiming that the value of a variable is not null. If a null value is passed unknowingly, it may cause difficulties in debugging as the error won't be caught until runtime


That's it for today. I hope you learned something new. You can reach out to me on:

  1. Twitter
  2. Showwcase
  3. GitHub

Did you find this article valuable?

Support Swapnil by becoming a sponsor. Any amount is appreciated!