我试图用一个常量对象替换一个使用硬编码字符串值的枚举,该常量对象使用来自联合的字符串值。
我希望能够指定在某些上下文中允许的联合的子集。
// 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操场上
任何帮助将不胜感激。
1条答案
按热度按时间oxalkeyp1#
如果后端类型发生变化,这将抛出一个错误:
要选择子集,请使用此类型:
希望这就是你要找的东西。