Non-null assertion operator ( ! )

  • A new ! post-fix expression operator may be used to assert that its operand is non-null and non-undefined.
  • By adding it we are saying to type-script that we need not check null or undefined on a object since i am most definite that its value will be present.
  • Note after transplantation of typescript, the ! symbol will not be present in the .js file

Below code will not compile with a null check of anchor variable :

const anchor = document.querySelector('a');
console.log(anchor.href); //Object is possibly 'null'.ts(2531)

But developer is a 100% sure that anchor will not be null, and checking null there or everyplace could increase the lines of code and also reduce code readability hence me can modify same piece of code and make it work just by adding ! to the end of it.

const anchor = document.querySelector('a')!;

Leave a Comment