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

Support simple check in if for discriminated unions with true/false discriminant #24843

Closed
4 tasks done
WiseBird opened this issue Jun 10, 2018 · 4 comments
Closed
4 tasks done

Comments

@WiseBird
Copy link

Search Terms

discriminated true false if

Suggestion

Use Cases

Having discriminated union with true/false discriminant:

interface Square {
    kind: true;
    size: number;
}
interface Rectangle {
    kind: false;
    width: number;
    height: number;
}

type Shape = Square | Rectangle;

we can treat them differently using verbose comparison in if:

let s: Shape = null;

if (s.kind === true) {
    console.log(s.size);
} else {
    console.log(s.height);
}

With simple check:

let s: Shape = null;

if (s.kind) {
    console.log(s.size);
} else {
    console.log(s.height);
}

ts doesn't recognize Rectangle in else branch: Property 'height' does not exist on type 'Square'

Examples

Would be nice to be able to do simple if(s.kind) check.

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript / JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. new expression-level syntax)
@MartinJohns
Copy link
Contributor

MartinJohns commented Jun 10, 2018

This works already if you enable strictNullChecks. If you don't enable strictNullChecks, then you need to explicitly check for false in your else block (aka else if (s.kind === false), because the value can be undefined and null too (tho theoretically TS could infer that it's not undefined / null because you accessed a property before).

@WiseBird
Copy link
Author

But this former check works without strictNullChecks:

if (s.kind === true) {
    console.log(s.size);
} else {
    console.log(s.height);
}

here too in else the value can be undefined or null.

@DanielRosenwasser
Copy link
Member

I think this is a duplicate of #10564.

@WiseBird
Copy link
Author

Duplicate

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants