Skip to content

type narrowing value on "deferred" let assignment does not work when equivalent non-"deferred" assignment does #33666

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
seansfkelley opened this issue Sep 30, 2019 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@seansfkelley
Copy link

TypeScript Version: 3.6.3

Search Terms: let inference inferred union type guard narrow defer deferred

Code

interface Success {
    success: true;
    response: object;
}

interface Error {
    success: false;
    error: object;
}

function request(): Success | Error {
    return null as any;
}

// This does not work:
let r;
r = request();

// This does:
// let r = request();

// The type information give on hover for `r` here is the same in both cases: `Success | Error`.
r;

if (r.success) {
    r.response;
}

Expected behavior: r.response is accessible within the block guarded by r.success. Changing the declaration of r to a single line let r = request(); has no effect.

Actual behavior: r is not type-narrowed, so r.response is not accessible. Changing the declaration to a single line resolves the issue.

Playground Link: https://www.typescriptlang.org/play/index.html#code/JYOwLgpgTgZghgYwgAgMoFcFIM7eQbwChkTltMdsAuZMKdCAbmNKgmwAcB7EbCGrgCMAVhARhmAX0KFQkWIhQBRKFC5QCLEuSztqyeABs+zUsmhqoAkWImFphGOhDjgPZGwCODbGAAUAJQ0GLq4yAA+yCqWmmZsYOhQIMgg6IaGyHB4cCAAnlIyAPSFyAAqABbAeAAmXOwpXGDIAO7qANZUhIYQTVDMGgC8HhDe7P4BzITFZZU1ddRTJd29yENePuOT0xUoYLkcKKAw6gC2cGBuyQDmwABuKO7lXPcaxxoABlDvyOXQh3hgX5kOAnQ7JQSNcrIBBZdg0d4hSgRKKqdTvAB0hD6MmAMGQfig6J0lACsVY6LYnB4JnsQA

Related Issues:

@RyanCavanaugh
Copy link
Member

Duplicate #30557

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Oct 14, 2019
@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

@seansfkelley
Copy link
Author

Confirmed as a duplicate: by explicitly annotating the "deferred" declaration

let r: Success | Error;

the type narrowing now works correctly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants