strictNullChecks - Best Practices

July 2017
July 2026

Should I use the strictNullChecks TypeScript compiler flag - yes or no?

Null pointers are one of the most common categories of bugs, yet they can be avoided to a large degree with the strictNullChecks TypeScript compiler flag. The strictNullChecks flag was added in TypeScript 2 and its usage is widespread by now. Angular, VSCode, RxJS and Babylon.js all use it, and it's part of the strict flag that tsc --init enables for new projects. The bare compiler still defaults to strictNullChecks: false though. The reason for this is backwards compatibility and to keep TypeScript a superset of JavaScript.

If you're starting a new TypeScript project or you find the time to introduce the strictNullChecks flag to your existing project, I would recommend doing so. On the upside you'll get more safety added to your application at compile time, which is almost always a good thing. Having strict null checks also doesn't clutter up your code, since those are checks that your application should include anyways. On the downside there's one more concept for new developers to learn. To me, the pros outweigh the cons so I would recommend turning strict null checks on.

An example of strict null checks would be:

tsconfig.json
{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "noImplicitAny": true,
    "strictNullChecks": true,
    "outDir": "./dist"
  },
  "include": [
    "src/**/*"
  ]
}
src/user.ts
interface User {
  name: string;
  age?: number;
}
function printUserInfo(user: User) {
  console.log(`${user.name}, ${user.age.toString()}`)
  // => error TS2532: Object is possibly 'undefined'.
  console.log(`${user.name}, ${user.age!.toString()}`)
  // => OK, you confirm that you're sure user.age is non-null.

  if (user.age != null) {
    console.log(`${user.name}, ${user.age.toString()}`)
  }
  // => OK, the if-condition checked that user.age is non-null.

  console.log(user.name + ', ' + user.age != null ? user.age.toString() : 'age unknown');
  // => Unfortunately TypeScript can't infer that age is non-null here.
}

You can check for yourself at the typescript playground.

As you can see, the exclamation point denotes that you are sure (e.g. by performing a check somewhere in the code) that something that’s potentially null actually isn’t. If you perform an if-check, TypeScript can infer that something is non-null. However, for the ternary operator this is unfortunately not the case.

Tax Wealth, Not Work
Wages get taxed to the bone while the ultra-rich watch their assets compound untouched — and then buy up the houses you're saving for. If you work for your money, this is your fight too.
Watch on YouTube →