Skip to content

GADT distinguished by boolean property not narrowed on test for truthiness #13464

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
svieira opened this issue Jan 13, 2017 · 2 comments
Closed
Labels
Duplicate An existing issue was already created

Comments

@svieira
Copy link

svieira commented Jan 13, 2017

I have a Success / Failure tagged union type called Result, where the tag property is of the one of the two literal types in boolean. Success uses the literal type true and Failure uses the literal type false. I would expect that a test like if (someResult.success) would narrow the type in the else branch to Failure, but it does not.

TypeScript Version: 2.1.4-insiders.20161201 (on the Playground)

Code

type Success<T> = { success: true, result: T };
type Failure = {success: false, err: Error};
type Result<T> = Success<T> | Failure;

// Also possibly a bug - type assertion is necessary too
// Otherwise r is upcast to a Success<T> in spite of the type ascription
const r: Result<number> = { success: true, result: 1 } as Result<number>;

if (r.success) {
  r.result;
} else {
  r.err
}

Expected behavior:

No compilation error

Actual behavior:
Compilation error at the r.err:

Property 'err' does not exist on type 'Result'.
Property 'err' does not exist on type 'Success'.

@ahejlsberg
Copy link
Member

Duplicate of #10564. It works as expected in --strictNullChecks mode.

The behavior without the as assertion is expected because control flow analysis has narrowed the actual type of r to Success<number>.

@ahejlsberg ahejlsberg added the Duplicate An existing issue was already created label Jan 13, 2017
@svieira
Copy link
Author

svieira commented Jan 13, 2017

Fantastic - thanks for the explanation!

@svieira svieira closed this as completed Jan 13, 2017
@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
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

2 participants