【问题标题】:What's the meaning of typeof Array[number] in Typescript?Typescript中typeof Array[number]是什么意思?
【发布时间】:2020-04-19 19:56:05
【问题描述】:
const names = ['jacob', 'master jung', 'kyuhyun'] as const;
type Names = typeof names[number];

我得到了我想要的结果,但我不明白typeof names[number]

Typescript 中的typeof Array[number] 是什么意思?

【问题讨论】:

  • 另外编辑器也不提供关于数字的提示。

标签: typescript typeof


【解决方案1】:

用户@jcalz 制作了一个comment,解释了它的工作原理。引用如下代码,与OP代码类似:

const fruit = ["apple", "banana", "grape"] as const;
export type Fruit = (typeof fruit)[number]; 'apple'|'banana'|'grape';

typeof fruitArray<"apple" | "banana" | "grape">,所以 Fruit 是 相当于(Array<"apple" | "banana" | "grape">)[number]。这 语法T[K] 表示:T 的属性类型,其键为 K 类型。所以(Array<"apple" | "banana" | "grape">)[number] 意味着 "Array<"apple" | "banana" | "grape"> 的属性类型 其键的类型为 number",或者:" Array<"apple" | "banana" | "grape">,或:"apple" | "banana" | "grape"

该用户的另一个类似comment 添加了更多技术术语:

T[K] 类型是 lookup type,它获取属性的类型 T 的密钥是 K。在(typeof list)[number],你得到 (typeof list) 的属性类型,其键为 number。像typeof list 这样的数组有numeric index signatures, 所以他们的number 键产生所有数字索引的联合 属性。

【讨论】:

    【解决方案2】:

    typeof 获取names 变量的类型(即readonly ['jacob', 'master jung', 'kyuhyun']),然后解析数组/元组成员类型。这称为索引访问类型或lookup types

    在语法上,它们看起来与元素访问完全一样,但写成类型

    在这种情况下,我们“查询”元组成员的类型(索引处的元组/数组),即'jacob' | 'master jung' | 'kyuhyun'

    Playground

    【讨论】:

      【解决方案3】:

      Names 类型的任何内容都必须是数组中的一个项目。

      现在,你可以这样做了:

      const value: Names = "jacob"
      

      【讨论】:

        猜你喜欢
        • 2019-08-18
        • 2019-12-26
        • 2017-05-25
        • 2010-11-19
        • 1970-01-01
        • 1970-01-01
        • 2016-07-14
        • 1970-01-01
        相关资源
        最近更新 更多