You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
interfaceCaseA{valueA: any;}interfaceCaseB{valueB: any;}typeOneOf={$case: "caseA";caseA: CaseA;}|{$case: "caseB";caseB: CaseB;}declareconstrequest: OneOf// I know that without further checks, on Typescript side, on the OneOf type, we're only sure that// `$case` exists and we're unsure about the rest. Yet, as human looking at this type, I know we'll// have either the caseA or caseB and therefore accessing the OneOf type by its $case should result// in a type of `CaseA | CaseB`. Is there any way of making this work?request[request.$case]
When using a oneOf with a discriminator, you can now access directly the value by doing yourOneOfVariable[yourOneOfVariable.discriminator] and it'll give you the union of the values.
π» Use Cases
What do you want to use this for?
We have a lot of oneOf equivalent in our codebase, especially as we're using protobuf and this is a very classic usecase.
What shortcomings exist with current approaches?
Not even sure this can be achieve in a type safe way currently?
What workarounds are you using in the meantime?
Casting the variable as any and then using as again to cast to the union type.
Thanks James Browning (@Jamesernator) it always hard to find the correct name of the feature one is looking for, but TIL about depending typing :) !
James Wyatt Cready-Pyle (@jcready) it is indeed except that this bit is not done on our side it's generated by a 3rd party lib. I'd need to see if we can tweak it somehow through configuration.
Hopefully dependant typing lands one day though π€
Activity
Jamesernator commentedon Jul 5, 2024
This is dependent typing which TypeScript doesn't support.
(There is a draft for a weak form of dependent typing, but I don't think is strong enough for the behaviour wanted here)
jcready commentedon Jul 5, 2024
The better way to model the one of is like this:
Now you can just access
request.$valueand the type will beCaseA | CaseBand you can refine the type by branching off therequest.$case.maxime1992 commentedon Jul 5, 2024
Thanks James Browning (@Jamesernator) it always hard to find the correct name of the feature one is looking for, but TIL about depending typing :) !
James Wyatt Cready-Pyle (@jcready) it is indeed except that this bit is not done on our side it's generated by a 3rd party lib. I'd need to see if we can tweak it somehow through configuration.
Hopefully dependant typing lands one day though π€
jcalz commentedon Jul 5, 2024
Essentially the same problem as #30581 and TS's facility to deal with it is described in #47109. The example here could look like
Playground link
typescript-bot commentedon Jul 12, 2024
This issue has been marked as "Duplicate" and has seen no recent activity. It has been automatically closed for house-keeping purposes.