简体   繁体   English

选择嵌套的Typescript类型Generics Inside Array

[英]Selecting Nested Typescript Type Generics Inside Array

I have the following generated type from a GraphQL query. 我有一个来自GraphQL查询的以下生成类型。

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. 我有一个React函数,用于从上面的查询中传递用户。

function userCard({ user }) {
   // ...do stuff
}

My question is how do I select the User subset from DealFragmentFragment ? 我的问题是如何从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? DealFragmentFragment["users"]获取数组的“内部”并且可能显示idname属性后会发生什么?

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 . 现在user显示属性idname Thanks to How to get Type of Array in Typescript generics 感谢如何在Typescript泛型中获取数组类型

If anyone has a better solution, please post it and I'll accept it. 如果有人有更好的解决方案,请发布它,我会接受它。 But otherwise this worked for me! 但除此之外,这对我有用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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