typescript - 有没有办法以数字形式获取元组的键?

标签 typescript generics tuples

考虑我有一些元组类型:

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

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

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

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

number | "0" | "1" | "2" | "length" | "toString" | "toLocaleString" | "pop" | "push" | "concat" | "join" | "reverse" | "shift" | "slice" | "sort" | "splice" | "unshift" | "indexOf" | ... 14 more ... | "values"

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

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

但是这个给了我字符串:

"0" | "1" | "2"

有没有一种方法可以在不硬编码任何内容的情况下获取数字?

Demo

最佳答案

这可以通过 recursive conditional types 来完成(在 Typescript 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


另一个更简单的解决方案(使用较旧的 typescript 版本):

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

关于typescript - 有没有办法以数字形式获取元组的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58563262/

相关文章:

reactjs - 当带有错误 props 的 React 功能组件 (React.FC<Props>) 作为 props 发送时,Typescript 不会提示吗?

javascript - typescript 绑定(bind)问题

java - 绕过运行时缺少 Java 泛型,将父类(super class)型绑定(bind)到子类实例

java - 泛型 Java 8 上的调用方法

c# - Action<T> 还是 Action<in T>?

python - 将元组的字符串转换为元组

使用 typescript 和 npm 将外部组件导入到 angular2 快速启动项目中

c# - 为什么我无法在 C# 中序列化元组?

java - 使用第二个列表作为键过滤 Scala 元组列表(元组内)

tdd - TypeScript 中的依赖注入(inject)