Skip to content

Array.filter does not properly narrow down typeΒ #52247

Closed as not planned
Closed as not planned
@bpasero

Description

@bpasero

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[].

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