Guilhem Soulas
Guilhem Soulas

Reputation: 1995

Typescript strictNullChecks syntax

I'm using the strictNullChecks flag in my Typescript project.

Consider the function below:

function hello(a: string | null) {
  if (a !== null) {
    console.log(a.length); // Here, "a" can only be a string
  }
}

The compiler works perfectly here.

However if I write instead if (typeof a !== "null") or even lodash's if (!_.isNull(a)) the compiler won't understand and will complain that a can possibly be null.

Is there any way to have these alternative syntaxes work too?

Upvotes: 0

Views: 115

Answers (1)

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 220884

However if I write instead if (typeof a !== "null") or ... the compiler won't understand and will complain that a can possibly be null.

This is a good thing because typeof null === "object", not "null". TypeScript does not consider non-working ways of testing for null to be correct.

Upvotes: 2

Related Questions