Reputation: 1983
I have the following generated type from a GraphQL query.
type Maybe<T> = T | null
...
export type DealFragmentFragment = { __typename: "Deal" } & Pick<
Deal,
"id" | "registeringStateEnum" | "status" | "offerStatus"
> & {
users: Maybe<Array<{ __typename: "User" } & Pick<User, "id" | "name">>>
>
I have a React function that takes a User passed down from the above query.
function userCard({ user }) {
// ...do stuff
}
My question is how do I select the User subset from DealFragmentFragment
?
function userCard({ user }: { user: DealFragmentFragment["users"] }) {
// ...do stuff
}
What goes after DealFragmentFragment["users"]
to get "inside" of the array and Maybe to show the id
and name
properties?
Thank you!
Upvotes: 2
Views: 681
Reputation: 1983
I needed a helper...
type Unarray<T> = T extends Array<infer U> ? U : T;
Then...
function userCard({ user }: {user: Unarray<DealFragmentFragment["users"]> }) {
// ...do stuff
}
Now user
shows properties id
and name
. Thanks to How to get Type of Array in Typescript generics
If anyone has a better solution, please post it and I'll accept it. But otherwise this worked for me!
Upvotes: 3
Reputation: 868
If you want to extract the type of nested element from array, you can do this:
// Let's assume the following is your result array:
const result = [{user: {id: 1, name: "abc"}}];
type t1 = typeof result // this will give you the type of the array
type t2 = typeof result[0] // This will give you the type of the element in the array.
type userId = typeof result[0][0] // Gives you the first key of the first element of the array.
Upvotes: 0