Here's a suggestion that might be helpful:
type OneOfConverter<T extends { element: { $case: PropertyKey } }> = {
[U in T["element"] as U["$case"]]: U["$case"] extends keyof U ? U[U["$case"]] : never
}
This code snippet utilizes key remapping in mapped types to go through the union members of T['element']
and assign each member to a type parameter U
. The key we are interested in is U["$case"]
.
We want to access the value within U
using this key, so we do U[U["$case"]]
. However, to handle cases where the property may not exist, we perform a conditional type check
U["$case"] extends keyof U
to make sure the key exists in
U
. If it does, we fetch the property value as
U[U["$case"]]
; otherwise, we return
never
.
Let's test it out:
type ObjectType = OneOfConverter<UnionType>;
// type ObjectType = {
// a: number;
// b: string;
// c: boolean;
// };
Seems to be working fine!
Playground link to view code