Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can TypeScript warn me about superfluous uses of the non-null assertion operator?

Tags:

typescript

Consider the following TypeScript code:

let x = { foo: { bar: "baz" } };
console.log(x.foo!.bar);

Here, the inferred type of x.foo is { bar: string }, and so there is no need for the use of the non-null assertion operator ! (see e.g. https://github.com/Microsoft/TypeScript/issues/7395): the compiler already knows that x.foo cannot be null.

Can tsc (or possibly a widely-used third party tool like TSLint) warn me about these superfluous uses of !, and/or is this a planned feature?

I'm sure this is feasible in principle (seems like this'd just be a matter of using the TypeScript compiler API to identify places where ! is used on variables whose type is not T | null or T | undefined); I'm just wondering if the heavy lifting has already been done. Or, I guess, a pointer to the relevant parts of the TypeScript compiler API would work too - it's tough finding documentation for it (I guess because it's not yet stable).

(The reason I ask is that I'm concerned that I'm going to end up having to deal with code where past me some idiot sprinkled ! everywhere to make tsc --strictNullChecks stop issuing errors, without actually thinking about whether the asserted variable actually will be non-null at runtime. If it does end up null at runtime, voila! A bug that we could've caught at compile time, but didn't because of overzealous !. The presence of !s on variables already known to be non-null would strongly hint that the code is overusing !, likely incorrectly.)

like image 362
senshin Avatar asked Jan 03 '17 22:01

senshin


1 Answers

TSLint does this now, via the no-unnecessary-type-assertion rule.

Code like this:

const x: string = "foo";
const y = x!.indexOf("f"); // <-- x is of type string; no need to assert non-null

Will trigger a warning something like this:

This assertion is unnecessary since it does not change the type of the expression.
like image 111
senshin Avatar answered Nov 08 '22 14:11

senshin