Should Limit number
based off if
guard
#56014
Labels
Suggestion
An idea for TypeScript
Too Complex
An issue which adding support for may be too complex for the value it adds
π Search Terms
if guard for number
π Version & Regression Information
β― Playground Link
https://www.typescriptlang.org/play?#code/C4TwDgpgBAsiDKkDGBLAhgGwHIFcC2UAvFAAxQA+UAjBVAEy0DMA3AFCtID2AdgM7BQ8IAIIAnUUSgBtAEQpgEPFRkAaKHIV46q9fMWMZAXTYYIAoQDVMALlgJk6bPkkk2KAGZQAFELGiAdKbcAObAABZQADzEjACUUADerFCCIFYYkr7i-u4o3AAmAJIFEAAeXrxEAHxQlYT1upra8QDU1MxQAPSdUAAq4NAQ4pyirAC+rEA
π» Code
π Actual behavior
Type error on this line
myVal = myArr.findIndex(s => s === "item2") + 1; // Type error
π Expected behavior
No type error.
I would expect no type error here because TypeScript has some really good type inference around
if
branches andtypeof
. This is really handy I would expect it to handle the problem above. Here is why I think TS should handle the case above:if
check to determine if I have less than 3 items in my array so that I can usefindIndex
to get the index of my element and add one to get the position in the list (note this still breaks if I remove the+ 1
at the endOrdinarily, one might say that
findIndex
could return something above my limiting type; that is true except I have anif
statement guaranteeing that won't be a problem. In a sense, it is a kind of guard.The main counter argument to this might be that we can't do anything about the arbitrary
+ 1
at the end. This is where my very limited knowledge of how TS works shows. I'm not sure if it would be possible to account for that, but I wouldn't think it impossible.Additional information about the issue
No response
The text was updated successfully, but these errors were encountered: