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

  1. MartinJohns commented on Aug 23, 2020

    @MartinJohns
    Contributor

    Duplicate of #9998.

  2. typescript-bot commented on Aug 26, 2020

    @typescript-bot
    Contributor

    This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

  3. locked as resolved and limited conversation to collaborators on Oct 21, 2025
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