【发布时间】:2021-06-21 11:04:17
【问题描述】:
我有一个常量字符串数组,例如
const emojis = ['????', '????', '????', '????', '????'] as const
我想要一个包含该数组索引联合的类型,例如
type emojiIndexes = IndexesOfArray<typeof emojis> // => 0 | 1 | 2 | 3 | 4
所以我不允许使用 number 并且只使用数组中索引的确切数量
如果数组大小例如
// changed from this
// const emojis = ['????', '????', '????', '????', '????'] as const
// to this
const emojis = ['????', '????', '????'] as const // removed 2 emojis
比,IndexesOfArray<typeof emojis> 将是 0 | 1 | 2
我如何创建IndexesOfArray 来创建具有常量数组索引的联合类型?
【问题讨论】:
标签: typescript typescript-generics