everyday: Development Log

01.01.2022 - TypeScript/Non-null assertion operator

Sometimes, you'll run into a case where TS keeps complaining about a value that is possibly undefined. For example:

const numToString = (a?: number) => {
  return a.toLocaleString();
  // Error: 'a' is possibly 'undefined'.

The proper way to handle this error is to actually check if a is valid before returning any values:

if (a) {
  return a.toLocaleString();
} else {
  return "Failed";

But if you are sure that a will never be null or undefined, you can add ! to stop TS from complaining:

const numToString = (a?: number) => {
  return a!.toLocaleString();

What happen if a is still undefined at runtime? Your program will crash, of course.

Read more