Skip to content

Instantly share code, notes, and snippets.

@ithinkdancan
Last active November 27, 2021 17:48
Show Gist options
  • Save ithinkdancan/e06c17583bc5beeebdfc1b6db23c82aa to your computer and use it in GitHub Desktop.
Save ithinkdancan/e06c17583bc5beeebdfc1b6db23c82aa to your computer and use it in GitHub Desktop.
Helper util for pulling union GQL types into named objects based on their __typename
/* based on https://github.com/artsy/artsy.github.io/issues/495#issuecomment-509697859 as https://artsy.github.io/blog/2018/10/19/where-art-thou-my-error/ */
type OfUnion<T extends { __typename: string }> = {
[P in T['__typename']]: Extract<T, { __typename: P }>;
};
const dataByTypename = <T extends { __typename: string }>(data?: T): OfUnion<T> => {
const typedData = data
? {
[data.__typename]: data,
}
: {};
return typedData as OfUnion<T>;
};
export default dataByTypename;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment