Skip to content

Narrowed types from user defined type guards are lost in subsequent method calls #20186

Closed

Description

TypeScript Version: 2.6.1.

Code

{
    // no error
    const arr1: Array<number> = ['foo', 1].filter(
        (x): x is number => typeof x === 'number',
    );

    /* unexpected error:
[ts]
Type '(string | number)[]' is not assignable to type 'number[]'.
Type 'string | number' is not assignable to type 'number'.
Type 'string' is not assignable to type 'number'.
*/
    const arr2: Array<number> = ['foo', 1]
        .filter((x): x is number => typeof x === 'number')
        .map(x => x);

    // workaround. no error
    const arr3: Array<number> = ['foo', 1]
        .filter((x: any): x is number => typeof x === 'number')
        .map(x => x);
}

Related ReactiveX/IxJS#162

Activity

  1. trxcllnt commented on Nov 21, 2017

    @trxcllnt

    possibly related to #19334. defining the type-guard predicate before the filter call works fine:

    function isNumber(x: string | number): x is number {
      return typeof x === 'number';
    }
    // no error
    const arr: Array<number> = ['foo', 1].filter(isNumber).map((x) => x);
  2. trxcllnt commented on Nov 21, 2017

    @trxcllnt

    Oliver Joseph Ash (@OliverJAsh) based on #19640 (comment) it looks like this may be fixed by #17600, as this form also works in 2.6.1:

    // no error
    const arr: Array<number> = ['foo', 1]
      .filter<number>((x): x is number => typeof x === 'number')
      .map((x) => x);
  3. ahejlsberg commented on Dec 3, 2017

    @ahejlsberg
    Member

    This is indeed fixed by #17600.

  4. ghost closed this as completedon Jan 4, 2018
  5. locked and limited conversation to collaborators on Jul 3, 2018
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

    BugA bug in TypeScriptFixedA PR has been merged for this issue

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions