To simplify this process, you can utilize a mapped type with keys renamed as shown below:
type InvitationMap = { [T in Invitation as NonNullable<T['__typename']>]: T }
In this instance, we are iterating through the type T
across the various members of union type within Invitation
. For each member T
, we aim to assign the property value as T
, and set the property key to be a string literal type derived from the __typename
property of T
. This can be achieved by using T['__typename']
with indexed access types, albeit with a minor caveat. Since the __typename
property is optional, the property type may include undefined
(e.g., 'ClientInvitation' | undefined'
or 'ExpertInvitation' | undefined'
). To swiftly eliminate undefined
, we can leverage the NonNullable<T>
utility type.
Upon inspecting the IntelliSense quick info for the InvitationMap
type:
/* type InvitationMap = {
ClientInvitation: {
__typename?: "ClientInvitation" | undefined;
email: string;
hash: string;
organizationName: string;
};
ExpertInvitation: {
__typename?: "ExpertInvitation" | undefined;
email: string;
hash: string;
expertName: string;
};
} */
With the defined InvitationMap
, you can easily reference it with the desired key:
type ClientInvitation = InvitationMap['ClientInvitation'];
/* type ClientInvitation = {
__typename?: "ClientInvitation" | undefined;
email: string;
hash: string;
organizationName: string;
} */
Link to code on Playground