Last active
November 27, 2021 17:48
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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