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

如何在TypeScript中动态创建支持嵌套变体访问的颜色对象类型?

实现嵌套式颜色变体的TypeScript类型

看起来你想要的是让每个颜色既是可直接访问的字符串值,同时又是包含变体属性的嵌套对象——之前的实现把变体拼接到了属性名上,确实不符合你的需求。这里有两种贴合需求的实现方案:

方案一:让颜色同时具备字符串和变体对象特性

这个方案最贴近你“直接通过颜色名称获取默认值,通过blue[20]获取变体”的需求,利用TypeScript的交叉类型让颜色同时成为string和带有变体属性的对象:

// 定义各颜色的变体集合(''代表默认值)
type BlueVariations = '' | 10 | 20 | 30 | 40;
type GreenVariations = '' | 20 | 40 | 60 | 80;

// 通用类型:生成同时包含默认字符串值和变体属性的颜色类型
type ColorWithVariations<Variants extends string | number> = 
  string & { [P in Exclude<Variants, ''>]: string };

// 最终的Colors类型
type Colors = {
  blue: ColorWithVariations<BlueVariations>;
  green: ColorWithVariations<GreenVariations>;
};

使用示例

通过Object.assign创建符合类型的对象(因为直接字面量无法同时定义字符串和附加属性):

const colors: Colors = {
  blue: Object.assign('#0070f3', {
    10: '#e6f2ff',
    20: '#ccdeff',
    30: '#99bfff',
    40: '#669eff'
  }),
  green: Object.assign('#2ecc71', {
    20: '#a2f5bf',
    40: '#57e389',
    60: '#22b573',
    80: '#16885a'
  })
};

// 直接获取默认色值
console.log(colors.blue); // 输出: '#0070f3'
// 获取指定变体色值
console.log(colors.blue[20]); // 输出: '#ccdeff'
console.log(colors.green[80]); // 输出: '#16885a'

方案二:纯嵌套对象结构

如果你更倾向于纯对象的直观结构,愿意通过blue['']来获取默认值,可以用这种更简洁的实现:

// 定义各颜色的变体集合(''代表默认值)
type BlueVariations = '' | 10 | 20 | 30 | 40;
type GreenVariations = '' | 20 | 40 | 60 | 80;

// 通用类型:生成包含所有变体(含默认值)的颜色对象类型
type ColorWithVariations<Variants extends string | number> = {
  [P in Variants]: string;
};

// 最终的Colors类型
type Colors = {
  blue: ColorWithVariations<BlueVariations>;
  green: ColorWithVariations<GreenVariations>;
};

使用示例

直接用字面量定义对象即可:

const colors: Colors = {
  blue: {
    '': '#0070f3',
    10: '#e6f2ff',
    20: '#ccdeff',
    30: '#99bfff',
    40: '#669eff'
  },
  green: {
    '': '#2ecc71',
    20: '#a2f5bf',
    40: '#57e389',
    60: '#22b573',
    80: '#16885a'
  }
};

// 获取默认色值
console.log(colors.blue['']); // 输出: '#0070f3'
// 获取指定变体色值
console.log(colors.blue[20]); // 输出: '#ccdeff'

两种方案都能满足你对不同颜色拥有独立变体集合的需求,你可以根据自己的使用习惯选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 08:59:05