gpt4 book ai didi

typescript - 获取数组文字的索引类型

转载 作者:行者123 更新时间:2023-12-04 12:40:50 25 4
gpt4 key购买 nike

假设我有以下数组文字:

const list = ['foo', 'bar', 'baz'] as const;

我正在尝试生成一个表示该数组可能索引的类型。我尝试按如下方式实现:

const list = ['foo', 'bar', 'baz'] as const;

type ListIndex = Exclude<keyof (typeof list), keyof []>;

但是 ListIndex 现在变成了 "0"| “1” | “2” 而不是 0 | 1 | 2

谁能告诉我如何获得所需的 0 | 1 | 2类型?

最佳答案

您可以使用以下类型:

type Indices<T extends readonly any[]> = Exclude<Partial<T>["length"], T["length"]>

让我们用 list 测试一下:

type Test = Indices<typeof list> // Test = 0 | 1 | 2 // works!

Live playground code

关于typescript - 获取数组文字的索引类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59184570/

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