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

TypeScript:如何用联合类型派生常量对象并指定允许子集?

解决方案

要实现基于联合类型的常量对象替代枚举,同时确保常量对象与后端生成的联合类型强关联,并且能安全定义子集,可按以下步骤处理:

1. 强关联常量对象与联合类型

使用TypeScript 4.9+的satisfies关键字,既能让常量对象保留字面量类型的精确性,又能确保其结构完全匹配后端生成的GeneratedWordStoreTypes:

// 后端Schema生成的联合类型
type GeneratedWordStoreTypes = "curriculum" | "departments" | "vertical-groups" | "year-groups" | "authors";

// 常量对象:键值严格匹配联合类型,且保留字面量类型
const WordStoreTypes = {
  curriculum: "curriculum",
  departments: "departments",
  "vertical-groups": "vertical-groups",
  authors: "authors",
  "year-groups": "year-groups",
} as const satisfies Record<GeneratedWordStoreTypes, GeneratedWordStoreTypes>;

如果你的TypeScript版本低于4.9,可通过辅助函数实现相同效果:

function createTypedRecord<T extends Record<GeneratedWordStoreTypes, GeneratedWordStoreTypes>>(obj: T): T {
  return obj;
}

const WordStoreTypes = createTypedRecord({
  curriculum: "curriculum",
  departments: "departments",
  "vertical-groups": "vertical-groups",
  authors: "authors",
  "year-groups": "year-groups",
} as const);

2. 定义并使用联合类型的子集

通过as const定义子集数组,再推导子集类型,就能实现赋值时的类型校验:

// 定义允许的子集:直接使用常量对象的属性值,避免硬编码拼写错误
const subsetOfAllowedTypes = [
  WordStoreTypes.authors
] as const;

// 推导子集的联合类型
type AllowedWordTypeType = typeof subsetOfAllowedTypes[number];

// ✅ 合法赋值:TypeScript允许
const validConstrainedType: AllowedWordTypeType = WordStoreTypes.authors;
// ❌ 非法赋值:TypeScript会抛出类型不匹配错误
const invalidConstrainedType: AllowedWordTypeType = WordStoreTypes.curriculum;

关键优势

  • 强类型校验:常量对象必须完全匹配后端生成的联合类型,避免手动维护时的遗漏或拼写错误;
  • 精确类型推导:as const保留了字面量类型,子集赋值时能精确校验;
  • 无硬编码冗余:子集直接复用常量对象的值,无需重复写字符串字面量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 12:04:52