← Back
typescript

Typescript's strict null check

TL;DR: strict null check has to be enabled explicitly in every project with this in tsconfig.json:

  "strictNullChecks": true,

If you enabled on an existing project, run the compiler to verify or find errors:

npx tsc -p .

How I discovered it #

We have this kind of code:

const user = await UserRepository.findOne({ id: 'nonsense-value' }
user.name = "This should fail"

In my mental model, this code shouldn't compile, but it does.

Let me explain the issue first. The function signature of findOne is this: findOne

That it means that the result of the promise (inside the user variable) should be User or undefined, but it's not: Inferred types by VSCode

It looks like TS is inferring "User" instead of "User | undefined". WTF!? We are loosing most of the benefits of the types! 😫

At the end, I discovered that you need to explicitly configure typescript to detect it.