Array.shift() should return defined for consistency with random access #51035
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
in:title array shift
#13778
β Viability Checklist
My suggestion meets these guidelines:
β Suggestion
Whether an array element is defined/undefined is inconsistent. If you use direct access it's always defined even when the control flow clearly indicates it couldn't possibly be; if you use method-based access it's always possibly undefined even when the control flow clearly indicates it must be defined.
The discussion for random access in #13778 ended in keeping it
defined
by default and adding a pedantic compiler flag for making it allundefined
. I'm proposing an extension of that toshift
and otherArray
methods that should, for consistency, follow the same behaviour.π Motivating Example
https://www.typescriptlang.org/play?#code/MYewdgzgLgBAZiEMC8MDaBGANAJiwZiwBYsBWAXQChRJYAjAQwCcUYAKAfQC4YwBXALZ0ApkwCUKAHwwOlauGgwAHqwQgAdBAAWASzhQ2EgPRHlMHRBh8wAE2FwdYYTZjCAbsLAwoWkHwDmWvCIMFoMlsIANsICnlCWdg5OLgx0IB6UjExsSsamUACeAA7CrkxMIExyNIoFqohoAJyN5DAmMHUWMImOzq4eXj5+gcFINiDClmAgsGEe3mGwAgxgdVExcRCZzGwFefC9cnrsaurRYP4+MNIADBIA3pQwzzA1sABe9Rraegb7n11rD1kv1PAthkEAO6lABWfEUwC0wmAAGs+qdzpcgrcni8smx3vtCiUyhUqgBfI5wdgAQjYGM8WLEDzapkqozOjKuyB5MBuMEhi3congkRADHiHT8LDSEtxzzeME+qDUTRarKV5gS9l6LmFg18AShsPhsERyLRLh0Zr8kRsYAA5LAiiAIBAdHRInURPKYPjCRqksJKJSgA
π» Use Case
I can understand that it always could be
undefined
, e.g. in this case:However, this is a rarer case than
x[n]
which is much more commonlyundefined
. Given thatx[n]
is by default assumeddefined
unless the--noUncheckedIndexedAccess
compiler flag is provided,.shift()
should follow the same pattern.Currently we use
.shift()
and a queue-based structure rather than random access, but TypeScript actually penalizes this. The only ways around this are assertions!
or adding an extra call for random access.Workaround 1 (
!
):Consider the following case as why this is a problematic anti-pattern:
Workaround 2 is more type-safe (extra call for random access):
However, this is an anti-pattern at best.
The text was updated successfully, but these errors were encountered: