strictNullChecks - Best Practices

July 2017
September 2017

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. Since the strictNullChecks flag was only added in TypeScript 2, its usage isn't that widespread yet. As of September 2017, the Angular project and the typeORM project are two examples that use the flag, while VSCode, RxJS, Ionic, or Babylon.js all don’t. Furthermore, strictNullChecks isn't the default for new TypeScript projects. 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.
}

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.

Interested in TypeScript?