Closed
Description
TypeScript Version: 3.2.2
Search Terms: Conditional Types, Type Guards, iterators, loop, callback functions
Suggestion:
When having values that are of union type and conditions result in telling the Typescript Type Guards to adjust the type, in basic Javascript iterator functions this adjusted type is reset to its initial type.
Code Example:
const myFunc = () => {
let myVal: string | undefined;
if (!myVal) return;
myVal; // Type = string
new Array(2).forEach(x => myVal); // Type = string | undefined
}
Expected behavior:
The type of myVal
in the last line should only be of type string
.
This would be nice for all iterators (e.g. for, while, map, …)
Actual behavior:
The type of myVal
is string | undefined
Info:
I don't know why, but the playground does not show the correct typing, please test in your code.
Checklist:
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.