TypeScript Version: 3.9.7
Search Terms:
type narrowing not working inside array forEach callback
Code
type Observer = {next:()=>void}
let observer: Observer|undefined
const value = {}
if (observer) {
Object.keys(value).forEach((name) => {
observer.next();
});
}
Expected behavior: No error, narrows type
Actual behavior: Error, doesn't narrow type
Playground Link: https://www.typescriptlang.org/play?#code/C4TwDgpgBA8gRgZwgJwG4qgXigbwHYQAewAXABQCUmAfKgPYCWAJgL4BQbANhMFHYinTISsAWhQAfAK54mEAGYMCTDgGM6eBL1QBDTlOjYc7Ng3lQy-JOOQVcbKKIBWEVcAB0AawggEZXfoQFO7ydMgAojqqABZkZHg6ALZBWNT2jo5WgijuBMSUANwOUCwURSxAA
Related Issues:
#36436
#9998
Work arounds
- enumerate the array even if i don't want to do any work (downside is its not performant)
- check if
observer is defined multiple times (downside is TS imposing on code readability)
if (observer) {
Object.keys(value).forEach((name) => {
if (observer) {
observer.next();
}
});
}
TypeScript Version: 3.9.7
Search Terms:
type narrowing not working inside array forEach callback
Code
Expected behavior: No error, narrows type
Actual behavior: Error, doesn't narrow type
Playground Link: https://www.typescriptlang.org/play?#code/C4TwDgpgBA8gRgZwgJwG4qgXigbwHYQAewAXABQCUmAfKgPYCWAJgL4BQbANhMFHYinTISsAWhQAfAK54mEAGYMCTDgGM6eBL1QBDTlOjYc7Ng3lQy-JOOQVcbKKIBWEVcAB0AawggEZXfoQFO7ydMgAojqqABZkZHg6ALZBWNT2jo5WgijuBMSUANwOUCwURSxAA
Related Issues:
#36436
#9998
Work arounds
observeris defined multiple times (downside is TS imposing on code readability)