选择数组内的嵌套Typescript类型泛型

时间:2019-04-18 05:02:19

标签: javascript reactjs typescript graphql

我从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">>>
    >

我有一个React函数,该函数接受从上述查询中传下来的一个用户。

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

我的问题是如何从DealFragmentFragment中选择“用户”子集?

function userCard({ user }: { user: DealFragmentFragment["users"] }) {
   // ...do stuff
}

DealFragmentFragment["users"]之后进入数组的内部并且也许显示idname属性之后会发生什么?

谢谢!

2 个答案:

答案 0 :(得分:0)

如果要从数组中提取嵌套元素的类型,可以执行以下操作:

// 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 :(得分:0)

我需要一个帮手...

type Unarray<T> = T extends Array<infer U> ? U : T;

然后...

function userCard({ user }: {user: Unarray<DealFragmentFragment["users"]> }) {
   // ...do stuff
}

现在user显示属性idname。感谢How to get Type of Array in Typescript generics

如果任何人有更好的解决方案,请发布并接受。否则,这对我有用!