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

TypeScript:如何为以数组索引为键的泛型对象定义类型?

解决方案

要把数组类型转成以字符串格式索引为键的可选对象类型,只需修改映射类型的索引处理逻辑,把元组的数字索引转成字符串键即可:

export type DataTypes = string | number | Date;
// 补充ColumnConfig的基础定义(可根据实际场景替换)
type ColumnConfig<T extends DataTypes> = {
  label: string;
  value: T;
};
type ColumnConfigShort<T extends DataTypes> = Partial<ColumnConfig<T>>;

type ToColumnConfigShort<T> = T extends DataTypes
  ? T extends string
    ? ColumnConfigShort<string>
    : T extends number
    ? ColumnConfigShort<number>
    : T extends Date
    ? ColumnConfigShort<Date>
    : never
  : never;

// 关键修改:用as子句把数字索引转成字符串格式
type ColumnsConfigShort<T extends DataTypes[]> = Partial<{
  [I in keyof T as I extends `${infer N extends number}` ? `${N}` : never]: ToColumnConfigShort<T[I]>;
}>;

// 验证结果
type howItCanBeUsed = ColumnsConfigShort<[number, number, string]>;
// 生成的类型符合预期:
// {
//   "0"?: Partial<ColumnConfig<number>>;
//   "1"?: Partial<ColumnConfig<number>>;
//   "2"?: Partial<ColumnConfig<string>>;
// }

关键改动解析

  • 索引转换:通过as关键字对映射的索引I做类型判断,只保留数字类型的索引,并将其转换为字符串格式(比如0→"0"),自动过滤掉数组自带的length、push等非数字键。
  • 保留可选性:外层的Partial保证每个对象属性都是可选的,完全匹配你需要的结构。

内容的提问来源于stack exchange,提问作者Schaschlik

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 06:27:50