Skip to content

type narrowing not working inside array forEach callback #40202

@joshribakoff

Description

@joshribakoff

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();
      }
    });
  }

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions