Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

type narrowing not working inside array forEach callback #40202

Closed
joshribakoff opened this issue Aug 23, 2020 · 2 comments · Fixed by #56908
Closed

type narrowing not working inside array forEach callback #40202

joshribakoff opened this issue Aug 23, 2020 · 2 comments · Fixed by #56908
Labels
Duplicate An existing issue was already created

Comments

@joshribakoff
Copy link

joshribakoff commented Aug 23, 2020

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();
      }
    });
  }
@MartinJohns
Copy link
Contributor

Duplicate of #9998.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Aug 24, 2020
@typescript-bot
Copy link
Collaborator

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants