【问题标题】:Selecting Nested Typescript Type Generics Inside Array选择数组内的嵌套 Typescript 类型泛型
【发布时间】:2019-09-08 09:37:35
【问题描述】:

我从 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 属性?

谢谢!

【问题讨论】:

  • 如果你console.log(DealFragmentFragment["users"])你看到了什么?
  • 嗨@ManoshTalukder。这是一个错误。我不相信console.log 评估 TS 类型。上述代码的编译器状态为TypeScript error: Property 'user' does not exist on type 'Maybe&lt;({ __typename: "User"; } &amp; Pick&lt;User, "id" | "name"&gt;)[]&gt;'. TS2339

标签: javascript reactjs typescript graphql


【解决方案1】:

我需要一个帮手...

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

如果有人有更好的解决方案,请发布,我会接受。但除此之外,这对我有用!

【讨论】:

  • 谢谢!!!我对某些urql/prisma/nexus 一代有类似的问题,并且有完全相同的问题,而您的Unarray 解决了它!非常有帮助!
【解决方案2】:

如果你想从数组中提取嵌套元素的类型,你可以这样做:

// 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.

【讨论】:

  • 感谢您的回复! DealFragementFragment["users"][0] 返回Property '0' does not exist on type 'Maybe&lt;({ __typename: "User"; } &amp; Pick&lt;User, "id" | "name"&gt;)[]&gt;'.ts(2339)
猜你喜欢
  • 2019-05-06
  • 2019-03-10
  • 1970-01-01
  • 1970-01-01
  • 2020-06-29
  • 1970-01-01
  • 1970-01-01
  • 2019-05-30
  • 1970-01-01
相关资源
最近更新 更多