TypeScript
TypeScript copied to clipboard
Wrong casting on variable assigned array Element when array is empty
Bug Report
π Search Terms
π Version & Regression Information
- This is a crash
- This changed between versions ______ and _______
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about _________
- I was unable to test this on prior versions because _______
β― Playground Link
let numbersArr = []
if (Math.random() > 0.5) {
numbersArr.push(123)
numbersArr.push(29)
numbersArr.push(20)
}
// says its type number if you hover over but it could be undefined
let awesomeNumber = numbersArr[0];
console.log('typeof awesomeNumber', typeof awesomeNumber)
console.log(awesomeNumber)
// says number could be NaN
let coolNumber = 2 + awesomeNumber
### π Actual behavior
Typescript asserts the element is a number.
### π Expected behavior
The variable should be a number or undefined. Since the array may be empty and we are accessing the first element inside of it.
The provided is a simple one, but this actually happened with an array of objects. I was trying to access a property on one of the objects, and my app could crash, because sometimes that first element is not there and so it is undefined. I didn't do my optional chaining someObj?.objectProperty that I would normally do if warned my variable was undefined.
Thanks for looking
The option that controls this behavior is called noUncheckedIndexedAccess
; you need to enable it if you want the type to be number | undefined
Note that enabling noUncheckedIndexedAccess
will also affect indexing in e.g. for
loops, which might make the cure worse than the disease (hence why that option isnβt enabled by default)
Thanks folks appreciate the quick responses.