2

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!

2
  • If you console.log(DealFragmentFragment["users"]) what do you see? Commented Apr 18, 2019 at 5:16
  • Hi @ManoshTalukder. It's an error. I don't believe console.log evaluates TS types. The compiler for the above code states TypeScript error: Property 'user' does not exist on type 'Maybe<({ __typename: "User"; } & Pick<User, "id" | "name">)[]>'. TS2339 Commented Apr 18, 2019 at 5:24

2 Answers 2

3

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you!!! I had a similar issue with some urql/prisma/nexus generation and had the exact same question, and your Unarray solved it! Extremely helpful!
0

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.

1 Comment

thanks for your reply! DealFragementFragment["users"][0] returns Property '0' does not exist on type 'Maybe<({ __typename: "User"; } & Pick<User, "id" | "name">)[]>'.ts(2339)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.