Detect "partial aliased conditions" where string typeof is stored in a const, instead of boolean typeof === expression #49583
Labels
Awaiting More Feedback
This means we'd like to hear from more people who would be helped by this feature
Suggestion
An idea for TypeScript
Suggestion
π Search Terms
aliased conditional expressions, aliased condition, const typeof value, control flow analysis, type narrowing, type guards
β Viability Checklist
My suggestion meets these guidelines:
β Suggestion
TS 4.4 added "Control Flow Analysis of Aliased Conditions", which detects boolean consts that when used in conditionals should narrow the type. The suggestion here is to also detect & narrow the type when other consts (the string value of
typeof
) are incorporated inside boolean expressions (===
) in a conditional.π Motivating Example
(Playground)
Interestingly, it seems like this pattern is already supported for discriminated type unions β in the TS 4.4 release notes above, see the example that reads "Analysis on discriminants in 4.4 also goes a little bit deeper."
This suggestion might potentially apply to other kinds of value-driven type narrowing as well, e.g. truthy checks that act as non-nullable type guards β though that appears to not work yet even with directly inlined checks, so it probably shouldn't be in scope for this suggestion.
π» Use Cases
The specific example where I saw this was code that 'cached' the typeof result in a const because it had a chain of ifs checking for different type values.
The text was updated successfully, but these errors were encountered: