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

如何将TypeScript枚举的键转换为前缀为Can的布尔类型?

可行,以下是实现方案

你可以通过TypeScript的模板字符串类型和泛型实现这个需求,完全支持枚举集合不确定的场景,具体实现如下:

1. 基础类型转换(全枚举键生成Can前缀类型)

如果需要把枚举的所有键都转换成带Can前缀的boolean属性类型,直接用映射类型即可:

enum Thing {
  ValA = 'ValA',
  ValB = 'ValB',
  ValC = 'ValC'
}

// 生成所有带Can前缀的属性类型
type CanDos = {
  [K in keyof typeof Thing as `Can${K}`]: boolean;
};
// CanDos的结构:{ CanValA: boolean; CanValB: boolean; CanValC: boolean; }

2. 动态生成对应传入枚举值的类型

针对你需要的「传入部分枚举值,对应Can属性为boolean,未传入的为undefined」的场景,用泛型结合条件类型实现:

enum Thing {
  ValA = 'ValA',
  ValB = 'ValB',
  ValC = 'ValC'
}

function checkIt<T extends Thing>(things: T[]) {
  // 定义返回类型:传入的枚举值对应Can属性为boolean,其余为undefined
  type ResultType = {
    [K in keyof typeof Thing as `Can${K}`]: typeof Thing[K] extends T ? boolean : undefined;
  };

  const result = {} as ResultType;

  // 初始化所有未传入的属性为undefined
  (Object.keys(Thing) as Array<keyof typeof Thing>).forEach(key => {
    result[`Can${key}` as keyof ResultType] = undefined;
  });

  // 模拟检查逻辑:根据实际需求替换这里的赋值逻辑
  things.forEach(thing => {
    const key = Object.keys(Thing).find(k => Thing[k as keyof typeof Thing] === thing) as keyof typeof Thing;
    result[`Can${key}` as keyof ResultType] = true; // 可替换为实际检查结果(true/false)
  });

  return result;
}

// 使用示例
const result = checkIt([Thing.ValA, Thing.ValB]);
result.CanValA; // 类型为 boolean(实际值为true/false)
result.CanValB; // 类型为 boolean(实际值为true/false)
result.CanValC; // 类型为 undefined(实际值为undefined)

关键特性说明

  • 模板字符串类型:Can${K}自动为每个枚举键添加Can前缀,需TypeScript 4.1及以上版本支持。
  • 泛型捕获:通过泛型T捕获传入数组的枚举值联合类型,让返回类型动态匹配传入的集合。
  • 类型与运行时一致:先初始化所有属性为undefined,再为传入的枚举值设置boolean结果,保证类型定义和实际运行行为完全匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 11:20:25