获取数组文字的索引类型

kla*_*man 4 typescript

假设我有以下数组文字:

const list = ['foo', 'bar', 'baz'] as const;
Run Code Online (Sandbox Code Playgroud)

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

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

type ListIndex = Exclude<keyof (typeof list), keyof []>;
Run Code Online (Sandbox Code Playgroud)

ListIndex现在变成"0" | "1" | "2"0 | 1 | 2

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

bel*_*a53 8

您可以使用以下类型:

type Indices<T extends readonly any[]> = Exclude<Partial<T>["length"], T["length"]>
Run Code Online (Sandbox Code Playgroud)

让我们测试一下list

type Test = Indices<typeof list> // Test = 0 | 1 | 2 // works!
Run Code Online (Sandbox Code Playgroud)

实时游乐场代码