简体   繁体   中英

Selecting Nested Typescript Type Generics Inside Array

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!

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM