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

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

Closed
OliverJAsh opened this issue Nov 21, 2017 · 3 comments
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue

Comments

@OliverJAsh
Copy link
Contributor

OliverJAsh commented Nov 21, 2017

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

@trxcllnt
Copy link

trxcllnt commented Nov 21, 2017

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);

@trxcllnt
Copy link

@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);

@mhegazy mhegazy added the Bug A bug in TypeScript label Nov 21, 2017
@ahejlsberg
Copy link
Member

This is indeed fixed by #17600.

@ahejlsberg ahejlsberg added the Fixed A PR has been merged for this issue label Dec 3, 2017
@mhegazy mhegazy assigned ghost and unassigned ahejlsberg Dec 4, 2017
@ghost ghost closed this as completed Jan 4, 2018
@mhegazy mhegazy added this to the TypeScript 2.7 milestone Jan 11, 2018
@microsoft microsoft locked and limited conversation to collaborators Jul 3, 2018
This issue was closed.
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue
Projects
None yet
Development

No branches or pull requests

4 participants