typeof
expressions should return an equivalent of a guard
#37868
Labels
typeof
expressions should return an equivalent of a guard
#37868
Search Terms
typeof guard array filter
Suggestion
Currently,
typeof
expressions return a boolean as expected. However, they are also special in that they narrow the types of their operands. In a similar vein, we can use type guards as the return value of functions to narrow(or assert) the types of their parameters:This is all fine, but suppose you write a very specific function:
This is IMO a special case that should be handled; particularly, when a
typeof
expression(or any expression that narrows a parameter's type) is the return value of a function, TS should infer that the function is a guard.Notice that, unlike the discussion in #6015, this issue is about the inferred type of a function which has a return value of a narrowing-expression. We could go further:
(by the way, I searched but couldn't find a similar one. If this is a duplicate I apologize!)
Use Cases
The most immediate use case is for array
filter
:I'm sure this type of change would make guards far more powerful as well, since we could create functions combine JS-checks(
typeof
,instanceof
) or even TS-checks(like discriminant variable checking) without having to explicitly write the guard expression(which, IMO is as good as a type assertion at the moment).Examples
(see above)
Checklist
My suggestion meets these guidelines:
This is possibly a breaking change, but IMO a good one as it would highlight actual programming errors for code that breaks
The text was updated successfully, but these errors were encountered: