TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Wrong casting on variable assigned array Element when array is empty

Open JSinkler713 opened this issue 2 years ago β€’ 2 comments

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

Workbench Repro


### πŸ™ 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


JSinkler713 avatar Nov 04 '22 17:11 JSinkler713

The option that controls this behavior is called noUncheckedIndexedAccess; you need to enable it if you want the type to be number | undefined

RyanCavanaugh avatar Nov 04 '22 17:11 RyanCavanaugh

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)

fatcerberus avatar Nov 04 '22 17:11 fatcerberus

Thanks folks appreciate the quick responses.

JSinkler713 avatar Nov 04 '22 19:11 JSinkler713