【问题标题】:Typescript type within object array notation对象数组表示法中的打字稿类型
【发布时间】:2022-01-23 05:47:13
【问题描述】:

我无法理解我在文件中看到的这段代码。这到底是为了什么?

const user = rowData as NonNullable<ApiResult["getUsers"]["data"][number]["users"]>[number];

如何使用类型(数字)来查看对象的属性?请注意,ApiResult 是一些 graphql 生成的类型,并且此代码位于 mui 数据网格 GridColumns 数组的 renderCell 中。

【问题讨论】:

  • "getUsers" 也是一个类型;这是一个字符串literal type。符号T[K]indexed access type,其中T 是类对象类型,K 是可分配给keyof T 的键类type,然后T[K] 是您的值类型'd 从索引到类型为T 的对象中获取,其键类型为K。如果fooFoo 类型,k"x" 类型,而foo[k]string 类型,那么Foo["x"]string 类型。
  • 嗯。嗯..是的..当然是的。

标签: typescript graphql


【解决方案1】:

如何使用类型(数字)来查看对象的属性?

数组是一个对象,并且在编号键处具有值,因此ArrayType[number] 将是数组中每个元素的类型的联合。


NonNullable&lt;Type&gt; 通过从Type 中排除nullundefined 来构造一个类型。

这是一个使用任意User 类型的数据结构预期扩展的示例。您可以访问 TS Playground 链接并将鼠标悬停在字母类型名称 AF 上,以查看 IntelliSense 认为这些类型是什么:

TS Playground

type User = {
  one: 'This is';
  two: 'the targeted type';
};

type ApiResult = {
  getUsers: {
    data: Array<{
      users: Array<User> | null | undefined;
    }>;
  };
};

declare const rowData: unknown;
const user = rowData as NonNullable<ApiResult["getUsers"]["data"][number]["users"]>[number];

// examine hierarchy:
type A = ApiResult
type B = ApiResult["getUsers"]
type C = ApiResult["getUsers"]["data"]
type D = ApiResult["getUsers"]["data"][number]
type E = ApiResult["getUsers"]["data"][number]["users"]
type F = NonNullable<ApiResult["getUsers"]["data"][number]["users"]>[number]

【讨论】:

  • 好的..谢谢。对我来说似乎是纯粹的精神错乱。
【解决方案2】:

以下是数组成员查找的一些简单示例:

const fruitsArray = ["apple", "orange"] as const;
type AvilableFruits = typeof fruitsArray[number]; // will be: "apple" | "orange"

const carsArray = [
  { make: "mercdes", class: "C" },
  { make: "mercdes", class: "S" }
] as const;
type AvilableMercedesClasses = typeof carsArray[number]["class"] // will be "C" | "S"

【讨论】:

    猜你喜欢
    • 2019-03-22
    • 1970-01-01
    • 2020-10-11
    • 2020-06-15
    • 2021-11-06
    • 2017-03-31
    • 2018-09-15
    • 2020-06-10
    • 1970-01-01
    相关资源
    最近更新 更多