假设我有以下数组文字:
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类型?
您可以使用以下类型:
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)
| 归档时间: |
|
| 查看次数: |
2645 次 |
| 最近记录: |