Typescript: Un-necessary compile warning: TS2454

Created on 24 Sep 2017  ·  3Comments  ·  Source: microsoft/TypeScript

Please see this screenshot:

screenshot 2017-09-23 15 41 31

In this case temp is declared already, but may never have been assigned. The if-check prevents using it, if it's not been assigned, so this compile warning may be unnecessary?

thanks

Question

Most helpful comment

let temp: string | undefined seems more accurate for that code in strict-null-checks world, and fixes the error as well.

All 3 comments

I understand your point, but most of the time "if" statements are used to check a variable's value, not to see whether it was assigned. This warning is useful because more often than not (at least in my experience and in most professional code I've seen) that situation is indeed not the programmer's intention.

As a side note, since "temp" is only defined inside that if statement, you can merge your two conditionals (unless path.normalize() can return a falsy value, in which case you can just assign a falsy value to temp in its declaration or in the else branch anyways).

let temp: string | undefined seems more accurate for that code in strict-null-checks world, and fixes the error as well.

A snippet of code that could be copied and pasted into a text buffer instead of a screenshot from an IDE is generally much more helpful.

Was this page helpful?
0 / 5 - 0 ratings