gpt4 book ai didi

typescript - Typescript 中 typeof Array[number] 的含义是什么?

转载 作者:行者123 更新时间:2023-12-04 12:05:56 28 4
gpt4 key购买 nike

const names = ['jacob', 'master jung', 'kyuhyun'] as const;
type Names = typeof names[number];

enter image description here

得到了想要的结果,但是看不懂 typeof names[number] .

什么 typeof Array[number]在 typescript 中是什么意思?

最佳答案

有一个comment由用户@jcalz 制作,解释了它是如何工作的。指的是如下代码,与OP代码类似:

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

typeof fruit is Array<"apple" | "banana" | "grape">, so Fruit isequivalent to (Array<"apple" | "banana" | "grape">)[number]. Thesyntax T[K] means: the type of the properties of T whose keys areof type K. So (Array<"apple" | "banana" | "grape">)[number] means"the types of the properties of Array<"apple" | "banana" | "grape">whose keys are of type number", or: "the array elements ofArray<"apple" | "banana" | "grape">, or: "apple" | "banana" | "grape".


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

The type T[K] is a lookup type which gets the type of the propertyof T whose key is K. In (typeof list)[number], you're gettingthe types of the properties of (typeof list) whose keys arenumber. Arrays like typeof list have numeric indexsignatures,so their number key yields the union of all numerically-indexedproperties.

关于typescript - Typescript 中 typeof Array[number] 的含义是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59541521/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com