Skip to content

Narrowing a type union with user-defined type guard #12235

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
lukaw3d opened this issue Nov 14, 2016 · 0 comments · Fixed by #12251
Closed

Narrowing a type union with user-defined type guard #12235

lukaw3d opened this issue Nov 14, 2016 · 0 comments · Fixed by #12251
Assignees
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue

Comments

@lukaw3d
Copy link

lukaw3d commented Nov 14, 2016

TypeScript Version: >= 2.0.2

Code

getResults1([]);
getResults1({data: []});

getResults2([]);
getResults2({data: []});


type Result = {value: string}
type Results = Result[];


function isResponseInData<T>(value: T | { data: T}): value is { data: T } {
    return value.hasOwnProperty('data');
}
function getResults1(value: Results | { data: Results }): Results {
    // error TS2322: Type 'Results | {data: Results}' is not assignable to 'Results'
    return isResponseInData(value) ? value.data  // value: {data: Results}
                                   : value;      // value: Results | {data: Results}   !!
}


function isPlainResponse<T>(value: T | { data: T}): value is T {
    return !value.hasOwnProperty('data');
}
function getResults2(value: Results | { data: Results }): Results {
    // Good
    return isPlainResponse(value) ? value        // value: Results
                                  : value.data;  // value: {data: Results}
}

Expected behavior:
Expected both getResults1 and getResults2 to compile fine, as they did in typescript@2.0.0 and typescript@1.8.10.

Actual behavior:
getResults1 doesn't compile, because value's type doesn't get narrowed in versions from typescript@2.0.2 forward (still an issue in 2.2.0-dev.20161114).

@ahejlsberg ahejlsberg added the Bug A bug in TypeScript label Nov 15, 2016
@ahejlsberg ahejlsberg self-assigned this Nov 15, 2016
@mhegazy mhegazy added this to the TypeScript 2.1.3 milestone Nov 15, 2016
@mhegazy mhegazy added the Fixed A PR has been merged for this issue label Nov 15, 2016
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
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

Successfully merging a pull request may close this issue.

3 participants