TypeScript:从联合体派生的常量对象,并指定允许的子集

0md85ypi  于 2023-04-07  发布在  TypeScript
关注(0)|答案(1)|浏览(101)

我试图用一个常量对象替换一个使用硬编码字符串值的枚举,该常量对象使用来自联合的字符串值。
我希望能够指定在某些上下文中允许的联合的子集。

// The previous enum
// The values are the API routes
enum WordTypesEnum {
  Curriculum = "curriculum",
  Departments = "departments",
  VerticalGroups = "vertical-groups",
  Authors = "authors",
  YearGroups = "year-groups"
}

// The union supplied by the backend schema. The goal is to replace the enum with an object
// that can use the values from this union.
type GeneratedWordStoreTypes = "curriculum" | "departments" | "vertical-groups" | "year-groups" | "authors";

// /**
//  * A non-working as const solution using a Record
//  */
// const WordStoreTypes: Record<GeneratedWordStoreTypes, GeneratedWordStoreTypes> = {
//   "vertical-groups": "vertical-groups",
//   "departments": "departments",
//   "authors": "authors",
//   "curriculum": "curriculum",
//   "year-groups": "year-groups",
// } as const

/**
 * This works when picking out the subsets, but is not using the generated types in construction.
 */
const WordStoreTypes = {
  "vertical-groups": "vertical-groups",
  "departments": "departments",
  "authors": "authors",
  "curriculum": "curriculum",
  "year-groups": "year-groups",
} as const

const subsetOfAllowedTypes = [
    "authors"
] as const;

type AllowedWordTypeType = typeof subsetOfAllowedTypes[number];

// This should be allowed by ts
const validConstrainedType: AllowedWordTypeType = WordStoreTypes.authors;
// This should cause a ts error
const invalidConstrainedType: AllowedWordTypeType = WordStoreTypes.curriculum;

这个代码也在TS操场上
任何帮助将不胜感激。

oxalkeyp

oxalkeyp1#

如果后端类型发生变化,这将抛出一个错误:

type ConstFromGeneratedTypes = { [K in GeneratedWordStoreTypes]: K }
    
    const WordTypesConst: ConstFromGeneratedTypes = {
        "curriculum": "curriculum",
        "departments": "departments",
        "vertical-groups": "vertical-groups",
        "authors": "authors",
        "year-groups": "year-groups"
    }

要选择子集,请使用此类型:

type AllowedWordType = Extract<GeneratedWordStoreTypes, "authors">

希望这就是你要找的东西。

相关问题