Skip to content

type narrowing not working inside array forEach callback #40202

Description

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

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions