Skip to content

Array.filter with a user-defined type guard predicate (arrow function) resolves to the wrong overload #20218

Closed
@afroozeh

Description

@afroozeh

TypeScript Version: 2.6.1

Code

interface Animal {
}

interface Cat extends Animal {
  meow(): void;
}

interface Dog extends Animal {
  bark(): void;
}

function isCat(animal: Animal): animal is Cat {
  return animal.hasOwnProperty("meow");
}

function isDog(animal: Animal): animal is Dog {
  return animal.hasOwnProperty("bark");
}

let animals: Animal[];

const cats: Cat[] = animals.filter(isCat);            // OK
const cats2: Cat[] = animals.filter(a => isCat(a));   // Type error

Expected behavior:
No errors

Actual behavior:

Error at cats2:

[ts]
Type 'Animal[]' is not assignable to type 'Cat[]'.
  Type 'Animal' is not assignable to type 'Cat'.
    Property 'meow' is missing in type 'Animal'.

The first call to filter on animals resolves to the function

filter<S extends T>(callbackfn: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[];

while the second call resolves to:

filter(callbackfn: (value: T, index: number, array: T[]) => any, thisArg?: any): T[];

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