Is there a way to configure ESLint to catch bad use of null-like values in typescript?

Viewed 638

For example, if I have this line of code:

const subject = collection.city?.person;

if(subject.name === "Jimmy") {
// do something
}

Static analysis tools yell at this line of code, for example, because they deem it "bad use of null-like values." Because if the subject is null, subject.name can't be defined. However, ESLint lets this go thru as a valid code.

Is there a way to configure ESLint to catch these types of errors before it gets to the static analysis tools at build time?

3 Answers

You can use TypeScript directly to enforce null checks, with strictNullChecks in your tsconfig:

When strictNullChecks is false, null and undefined are effectively ignored by the language. This can lead to unexpected errors at runtime.

When strictNullChecks is true, null and undefined have their own distinct types and you’ll get a type error if you try to use them where a concrete value is expected.

This will work much more effectively than ESLint's null enforcement, as it runs in the TypeScript compiler.

Please describe what type collection has, or better playground example. As with proper typing, TS will throw error on subject.name complaining subject can be undefined

check here: https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgCrIN4Chm+Q4MATwH4AuTAB2gGcB7ECjEOAWwgprClAHMBffliEIGXfHQA2kiAjDAGyCumQBeTEKyiQ4mgFcARgCtZYNROmmFIAHQFiJG9Sj0QAbixZgMABT7jpjYs7Gqq6gBEAFLArKxE4QCUmFgA9CnIACZ0yPTsYAAWfMJYQA

ESLint is not the tool for such checks, as deriving type of subject could be super complicated, and you'll basically end up with trying to implement in ESLint the same things what TS compiler does.

What you can do is run TS in 'check' mode alognside with ESLint. so it will not compile code but instead check it and fail same way as ESLint does it's check. this can be used as a CI step or commit/push hook. tsc --noEmit does the trick, with possible additional parameters depending on your case.

Related