Closed
Description
TypeScript Version: 3.4.0-dev.201xxxxx
Search Terms:
- array.pop
- Object is possibly 'undefined'
Code
const arr: string[] = [];
if (Math.random() > 0.5) { // <-- simulate runtime unknown array length
arr.push('hi');
}
if (arr.length > 0) {
arr.pop().toLowerCase(); // <-- error `Object is possibly 'undefined'`
}
Expected behavior:
No error, because we tested that the array's length was greater than zero.
Actual behavior:
Error: Object is possibly 'undefined'
Playground Link:
Note: turn on all strict checks in "options" (the link doesn't preserve these settings)
http://www.typescriptlang.org/play/index.html#src=const%20arr%3A%20string%5B%5D%20%3D%20%5B%5D%3B%0D%0A%0D%0Aif%20(Math.random()%20%3E%200.5)%20%7B%0D%0A%20%20%20%20arr.push('hi')%3B%0D%0A%7D%0D%0A%0D%0Aif%20(arr.length%20%3E%200)%20%7B%0D%0A%20%20%20%20%2F%2F%20NOTE%3A%20turn%20on%20all%20strict%20checks!%0D%0A%20%20%20%20arr.pop().toLowerCase()%3B%0D%0A%7D%0D%0A
Related Issues:
#29642 -- maybe? 🤔