typescript - 枚举的打字稿子集
问题描述
在打字稿中,我有一个像
export enum CarBrands {
Toyota = "TOYOTA"
Ford = "FORD"
.....
}
我想像这样创建这个枚举的一个子集,但似乎做不到
enum JapaneseCars {
CarBrands.Toyota
}
或创建具有子集的对象
const JapaneseCars = {
Carbrands.Toyota
}
无论如何我可以创建一个使用来自另一个现有枚举的值的对象或枚举?
我无法将 CarBrands 枚举更改为其他数据类型
解决方案
您可以创建一个type
和const
组合,其行为类似于作为另一个枚举子集的枚举。
缺点:此解决方案强制您让任何enum
' 的键与它们的值匹配(或者我还没有找到处理这种情况的解决方案)
// Given an enum
export enum CarBrand {
TOYOTA = 'TOYOTA',
FORD = 'FORD',
PEUGEOT = 'PEUGEOT',
RENAULT = 'RENAULT'
}
// We can create the type of the subset
export type FrenchCarBrand = Extract<CarBrand, CarBrand.PEUGEOT | CarBrand.RENAULT>;
// And the const that goes with it
export const FrenchCarBrand: Readonly<Record<FrenchCarBrand, FrenchCarBrand>> = {
[CarBrand.PEUGEOT]: CarBrand.PEUGEOT,
[CarBrand.RENAULT]: CarBrand.RENAULT
};
// With that you can :
// assign a CarBrand to a FrenchCarBrand ...
const a: FrenchCarBrand = CarBrand.RENAULT;
// ... as long as the CarBrand is in the type
const a_invalid: FrenchCarBrand = CarBrand.TOYOTA; // Type 'CarBrand.TOYOTA' is not assignable to type 'FrenchCarBrand'.
// assign a FrenchCarBrand to a CarBrand ...
const b: CarBrand = FrenchCarBrand.PEUGEOT;
// ... as long as the key exists
const b_invalid: CarBrand = FrenchCarBrand.TOYOTA; // Property 'TOYOTA' does not exist on type 'Readonly<Record<FrenchCarBrand, FrenchCarBrand>>'
// You cannot reassign the value of a FrenchCarBrand ...
FrenchCarBrand.PEUGEOT = CarBrand.RENAULT; // Cannot assign to 'PEUGEOT' because it is a read-only property.
// ... just like you cannot reassign the value of an enum
CarBrand.TOYOTA = 'MAZDA'; // Cannot assign to 'TOYOTA' because it is a read-only property.
如果你想将一个未知的类型值映射CarBrand
到一个类型的值FrenchCarBrand
,它不会起作用:
declare const brand: CarBrand;
const frenchBrand: FrenchCarBrand = brand; // Type 'CarBrand' is not assignable to type 'FrenchCarBrand'
// You can use the `as` keyword but it will hide bugs, so I do not recommend at all.
const frenchBrandNoError: FrenchCarBrand = brand as FrenchCarBrand; // No error, but a possible bug in your application.
为此,您需要一个类型保护:
export const isFrenchCarBrand = (brand: CarBrand): brand is FrenchCarBrand => {
return brand in FrenchCarBrand;
}
它将允许您决定在遇到不需要的值时该怎么做
if (isFrenchCarBrand(brand)) {
// You can safely assume that `brand` is a `FrendCarBrand`
} else {
// `brand` is definitely not a `FrendCarBrand`
}
推荐阅读
- java - 我可以一次声明一个数组并在整个代码中再次声明它吗?
- sql - 使用 Charindex 获取字符左侧的数据
- amcharts - 如何在不显示滚动条的情况下使 AMchart 4 水平滚动
- python - Watson Studio 的神经网络没有给出正确的输出格式
- elasticsearch - 术语聚合返回多个字段 (min_doc_count: 0)
- reactjs - 状态变量与 redux 中的 reducer 名称耦合
- wpf - 加入两个上下文菜单或将上下文菜单项绑定到父视图模型的命令
- css - 如何在此表单上创建叠加层
- google-sheets - 根据我的网站后端上的 ID 列更新谷歌表是否处于活动状态?
- android - 我无法为意图错误添加闹钟