有没有一种方法可以获取元组的键作为数字?

时间:2019-10-25 17:38:58

标签: typescript generics tuples

考虑我有一些元组类型:

type SomeTuple = ["a", "b", "c"];

现在我想以某种方式获取它的密钥作为数字:

type SomeTupleKeys<T = SomeTuple> = 0 | 1 | 2;

我尝试使用keyof SomeTuple,但它返回

  

编号| “ 0” | “ 1” | “ 2” | “长度” | “ toString” | “ toLocaleString” | “流行” | “推” | “ concat” | “加入” | “反向” | “移” | “切片” | “排序” | “拼接” | “换档” | “ indexOf” | ... 14更多... | “值”

我也尝试过更复杂的解决方案

type B = (SomeTuple extends infer T ? { [K in keyof T]: K extends keyof T ? K : never } : never)[number];

但这是给我的字符串:

  

“ 0” | “ 1” | “ 2”

有没有一种方法可以不用硬编码就可以获取数字?

Demo

1 个答案:

答案 0 :(得分:2)

一旦recursive conditional types的官方支持被发布(打字稿4.1),就有可能:

type TupleKeys<T extends ReadonlyArray<unknown>, Keys extends ReadonlyArray<number> = []> =
    T extends [infer _, ... infer R]
        ? TupleKeys<R, [R['length'], ...Keys]>
        : Keys[number];

type SomeTuple = ["a", "b", "c"];
type SomeTupleKeys = TupleKeys<SomeTuple>; // 0 | 2 | 1

Playground


另一个更简单的解决方案(已在使用较早的打字稿版本):

type TupleKeys<T extends Array<any>> = Exclude<Partial<T>['length'], T['length']>;

type SomeTuple = ["a", "b", "c"];
type SomeTupleKeys = TupleKeys<SomeTuple>; // 0 | 1 | 2

在这里,通过使用Partial,我们得到长度为0或1或2或3的元组的并集,然后排除3(原始元组的长度)

Playground