Non-null Assertion Operator

Sometimes the result may be null, like this.

const myApp = document.getElementById("app");

// const myApp: HTMLElement | null
myApp.style.width = '180px'; // error

We can use type assertions to solve this problem.

(myApp as HTMLElement).style.width = '180px'; // no error

Or we can use non-null assertion operator

myApp!.style.width = '180px';

! is a typescript not null assertion. The developers need to make sure that the value can not be null or undefined.

Optional chaining in JS, Stage 4

If we want to get properties in undefined, there will be an error. Like this.

const adventurer = {
    name: 'Alice',
    cat: {
      name: 'Dinah'
    }
  };

console.log(adventurer.dog.name) // VM101:1 Uncaught TypeError: Cannot read properties of undefined (reading 'name'))

To ensure that no errors occur, we can use optional chaining which is a symbol in JS

const dogName = adventurer.dog?.name; // no errors
console.log(dogName); // undefined

Note: It can only used in getter, not in setter.

Nullish coalescing operator, staging 4

Let's see Or operator before introducing Nullish coalescing operator

false || 2                   // 2
undefined || 2              // 2
null || 2                   // 2
1 || 2                      // 1
0 || 2                     // 2

So if the left-hand side logical result is false, then will return right-hand side operand.

But sometimes, We want to get 0 or false when the left-hand side operand is 0 or false. In other words, Only when left-hand side operand is undefined or null, we want to return right-hand side operand.

const foo = null ?? 'default string';
console.log(foo); // expected output: "default string"


const baz = 0 ?? 42;
console.log(baz); // expected output: 0