4

I've been using tslint for quite some time with no-null-keyword enabled. Recently, I've upgraded to Typescript 2.0 and enabled --strictNullChecking. However, looking at the Typescript's lib.d.ts, it appears impossible to keep no-null-keyword enabled (at first glance), since the result of some calls can be null. For example:

const result: RegExpExecArray | null = regex.exec(regexStr);

if (result === null) { // <-- tslint complains about this check
    throw new Error("Foo location: result of regex is null.");
}

// or
// if (result !== null) {
//     ...do  something
// }

The question is what is the-right-thing-to-do?

Disable no-null-keyword for tslint?

Use a hack (?):

const result: RegExpExecArray = regex.exec(regexStr)!;

if (result == undefined) { // Will check if result is undefined or null
    throw new Error("Foo location: result of regex is null.");
}

Or something else?

vladeck
  • 336
  • 3
  • 14

1 Answers1

6

no-null-keyword is just a lint rule. It's primary purpose is to prevent you from the added complexity of using both undefined and null for an often similar purpose.

But it doesn't remove it for your vendor codebase, and it is used in a lot of libraries.

result == undefined is indeed a perfectly valid JS idiom if you need to check for null and undefined values. This is not considered a hack (AFAIK) and is lot preferable to simple but dangerous Falsy checking: if (!result) {..}.

tslint even allows an exception for its === rule:

"triple-equals": [true, "allow-undefined-check"]

Benoit B.
  • 3,561
  • 24
  • 19
  • Yep, that is exactly what I was doing ever since I asked the question: `"triple-equals": [true, "allow-undefined-check"]` with code `foo == undefined` or `foo != undefined` along with an appropriate comment clarifying as to why. – vladeck May 10 '17 at 22:16
  • 1
    see [Question: Falsey values in JavaScript](https://stackoverflow.com/questions/3982663/falsey-values-in-javascript) on details why `(!result)` is dangerous – TmTron Oct 20 '18 at 09:30