Skip to content

Array.filter does not properly narrow down type #52247

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

Closed
bpasero opened this issue Jan 15, 2023 · 5 comments
Closed

Array.filter does not properly narrow down type #52247

bpasero opened this issue Jan 15, 2023 · 5 comments
Labels
Duplicate An existing issue was already created

Comments

@bpasero
Copy link
Member

bpasero commented Jan 15, 2023

Bug Report

πŸ”Ž Search Terms

array filter narrow down

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about: x

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

interface IFoo {
  foo: boolean;
}

interface IBar {
  bar: boolean;
}

const items: (IFoo | IBar)[] = [];

function isFoo(obj: unknown): obj is IFoo {
  if (!obj) {
    return false;
  }

  const candidate = obj as IFoo;
  return typeof candidate.foo === `boolean`;
}

const fooItems = items.filter(item => isFoo(item));
for (const fooItem of fooItems) {
  console.log(fooItem.foo); // error: Property foo does not exist on type IFoo | IBar
}

πŸ™ Actual behavior

The fooItems is of type IFoo | IBar

πŸ™‚ Expected behavior

I would have expected fooItems to be IFoo[].

@MartinJohns
Copy link
Contributor

filter() only narrows when you pass a type guard function. You don't do this.

@bpasero
Copy link
Member Author

bpasero commented Jan 15, 2023

How is function isFoo(obj: unknown): obj is IFoo { not a type guard function?

@MartinJohns
Copy link
Contributor

The inline function item => isFoo(item) is not. It lacks a type annotation, so the type is inferred to be boolean.

@bpasero
Copy link
Member Author

bpasero commented Jan 15, 2023

Cool thanks for the help! Very hard to figure this out though for me, even though having used TypeScript since 2012.

@fatcerberus
Copy link

See #38390

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Jan 24, 2023
@RyanCavanaugh RyanCavanaugh closed this as not planned Won't fix, can't repro, duplicate, stale Jan 24, 2023
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

No branches or pull requests

4 participants