Home > database >  Why does TypeScript allow checking against undefined?
Why does TypeScript allow checking against undefined?

Time:10-26

In the following example the variable boolOrNull is never undefined and the condition always true, why does TypeScript not complain?

let boolOrNull: boolean | null = null;
if (boolOrNull !== undefined) {
    console.log(123);
}

CodePudding user response:

Quoting Ryan Cavanaugh from this GitHub issue:

We intentionally allow this for the sake of defensive programming (i.e. defending against missing inputs from non-TS code). If there's enough demand we could add a flag or something.

That is, if your Typescript code ever has to interact with non-Typescript code, you may want to check that the non-Typescript code doesn't provide an undefined or null value where it isn't supposed to.

Of course, with the strictNullChecks flag enabled, Typescript code won't allow undefined to occur here, unless other unsafe code is used like accessing a missing property on a type with an index signature. However, one of Typescript's design principles is that it should accommodate idiomatic Javascript code, and it's fairly normal for Javascript programmers to compare values with undefined or null even when those values aren't supposed to ever be undefined or null.

As the quote above suggests, if a compiler flag enabling stricter checks like this would be useful to you, you could reply to the linked GitHub issue to give your feedback about it.

  • Related