« All posts

01.01.2022 - TypeScript / Non-null assertion operator

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

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

The proper way to handle this error is actually to 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 happens if a is still undefined at runtime? Your program will crash, of course.

Read more