-
Notifications
You must be signed in to change notification settings - Fork 12.8k
OneOf access by case and inference #59146
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
Comments
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) |
The better way to model the one of is like this: type OneOf = {
$case: "caseA";
$value: CaseA;
} | {
$case: "caseB";
$value: CaseB;
} Now you can just access |
Thanks @Jamesernator it always hard to find the correct name of the feature one is looking for, but TIL about depending typing :) ! @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 π€ |
Essentially the same problem as #30581 and TS's facility to deal with it is described in #47109. The example here could look like interface MyMap {
caseA: CaseA;
caseB: CaseB
}
type OneOf<K extends keyof MyMap = keyof MyMap> =
{ [P in K]: { $case: P } & Record<P, MyMap[P]> }[K]
function getVal<K extends keyof MyMap>(request: OneOf<K>): MyMap[K] {
const req: Record<K, MyMap[K]> = request;
return req[request.$case]
}
declare const request: OneOf
const either = getVal(request);
// ^? const either: CaseA | CaseB
declare const requestB: {$case: "caseB", caseB: CaseB};
const caseB = getVal(requestB);
// ^? const caseB: CaseB |
This issue has been marked as "Duplicate" and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
π Search Terms
β Viability Checklist
β Suggestion
Here's a very simple example:
Here's a link to a Typescript Playground
π Motivating Example
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
We have a lot of oneOf equivalent in our codebase, especially as we're using protobuf and this is a very classic usecase.
Not even sure this can be achieve in a type safe way currently?
Casting the variable as any and then using
as
again to cast to the union type.The text was updated successfully, but these errors were encountered: