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

TypeScript如何通过数组类型索引生成指定格式的联合类型

实现方案

可以实现,我们可以通过TS的模板字面量类型 + 递归工具类型完成需求,完整代码如下:

// 工具类型:生成 1 ~ N 的数字联合类型
type NumberRange<N extends number, Arr extends any[] = []> = 
  Arr['length'] extends N 
    ? Arr[number] 
    : NumberRange<N, [...Arr, [...Arr, 1]['length']]>;

// 通用主题颜色联合生成类型,传入符合结构的Theme类型即可生成对应联合
type ThemeColor<T extends { name: string; colors: any[] }> = 
  `${T['name']}-${NumberRange<T['colors']['length']>}`;

// ------------- 测试示例 -------------
type DefaultTheme = {
  name: 'default';
  colors: [string, string, string];
};
type CustomTheme = {
  name: 'custom';
  colors: [string, string, string, string, string];
};

// 结果符合预期:'default-1' | 'default-2' | 'default-3'
type DefaultColor = ThemeColor<DefaultTheme>;
// 结果符合预期:'custom-1' | 'custom-2' | 'custom-3' | 'custom-4' | 'custom-5'
type CustomColor = ThemeColor<CustomTheme>;

兼容泛型Theme场景

针对你提到的接收name和length入参的泛型Theme,也可以直接适配,示例如下:

// 可选:固定长度元组生成工具,用来给泛型Theme生成固定长度的colors字段
type FixedLengthArray<T, L extends number, Arr extends T[] = []> = 
  Arr['length'] extends L 
    ? Arr 
    : FixedLengthArray<T, L, [...Arr, T]>;

// 你的泛型Theme定义
type Theme<Name extends string, Length extends number> = {
  name: Name;
  colors: FixedLengthArray<string, Length>;
};

// 测试泛型场景
type MyTheme = Theme<'my', 4>;
// 结果:'my-1' | 'my-2' | 'my-3' | 'my-4'
type MyThemeColor = ThemeColor<MyTheme>;

注意事项

该实现依赖TS 4.1及以上版本引入的模板字面量类型特性,低于该版本的TS环境无法使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 00:24:04