You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建仅接受常量数组有效索引的TypeScript类型?

获取const数组的有效数字索引类型

给定如下常量数组:

const X = [{a: 3}, {a: 4}, {b: 6}] as const;

想要生成它的有效数字索引类型0 | 1 | 2,可以用以下几种方式实现:

方法一:过滤并转换数组的字符串索引

利用keyof获取数组类型的所有键,排除掉数组原型自带的属性和方法,再将剩余的字符串索引转换为数字类型:

const X = [{a: 3}, {a: 4}, {b: 6}] as const;

// 排除数组原型的键,得到字符串形式的索引
type ArrayStringIndices<T extends readonly any[]> = Exclude<keyof T, keyof any[]>;
// 将字符串索引转换为数字类型
type ArrayNumberIndices<T extends readonly any[]> = ArrayStringIndices<T> extends `${infer N extends number}` ? N : never;

type XIndices = ArrayNumberIndices<typeof X>; // 类型为 0 | 1 | 2

方法二:通过数组长度生成范围类型

递归生成从0到length-1的数字联合类型,适配任意长度的const数组:

const X = [{a: 3}, {a: 4}, {b: 6}] as const;

// 递归生成0到N-1的数字联合类型
type Range<N extends number, Acc extends number[] = []> = 
  Acc['length'] extends N ? Acc[number] : Range<N, [...Acc, Acc['length']]>;

type XIndices = Range<typeof X['length']>; // 类型为 0 | 1 | 2

补充说明

你之前尝试的keyof typeof X会返回数组的所有键,包括length、toString等原型属性,所以需要用Exclude过滤掉这些无关键,只保留数组的元素索引字符串,再转换为数字类型即可。

内容的提问来源于stack exchange,提问作者Robin De Schepper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 05:22:10