Nested Tagged Unions
See original GitHub issueTypeScript Version: 2.5.2
Code
type A = { type: "a", a: number }
type B = { type: "b", b: number }
type X = { type: A, a: string }
type Y = { type: B, b: string }
let x: X | Y
if (x.type.type === "a") {
x.a // Type Error
}
Expected behavior:
I would expect x to have type X
inside the if-statement after disambiguating the nested tagged union types.
Actual behavior:
Issue Analytics
- State:
- Created 6 years ago
- Reactions:76
- Comments:23 (6 by maintainers)
Top Results From Across the Web
Typescript Nested Tagged/Discriminated Union Types
If I try to model it using Typescript's discriminated unions, I'll face the problem that LoginReply needs to have a property kind with...
Read more >Nested Union Types - Learn - Elm Discourse
I have multiple union types that in turn belong to another union type like so: type Foo = OneFoo | TwoFoo | ThreeFoo...
Read more >Union declaration - cppreference.com
Optionally prepended by nested-name-specifier (sequence of names and ... Union-like classes can be used to implement tagged unions.
Read more >Tagged Unions and ReScript Variants - DEV Community
In TypeScript, we'd use a so called Discriminated Union Type (Tagged Unions) to be able to encode the conditional object shape within the ......
Read more >Zig Language Reference
Tagged union ; extern union; packed union; Anonymous Union Literals ... The struct is nested (declared) inside of a union. try expect(true); }...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
👋 currently there is a way (with some heavy type foo) to actually get this to work, I’ll use @rakeshpai example, but others should work as well:
You can read more about distributive conditional types here.
Also, I covered some of the building blocks for this solution ☝️ in this fan fiction story about typescript metaprogramming.
Hope this helps!
+1 here. I debugged this for a bit to realize that unions can only be discriminated at the top level / direct. I’m also copying fields down the chain for this purpose