Closed as not planned
Description
π Search Terms
- Generic derived value type
- oneOf
β Viability Checklist
- 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. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
- This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
β Suggestion
Here's a very simple example:
interface CaseA {
valueA: any;
}
interface CaseB {
valueB: any;
}
type OneOf = {
$case: "caseA";
caseA: CaseA;
} | {
$case: "caseB";
caseB: CaseB;
}
declare const request: 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]
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
- 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.