首页 > 解决方案 > 枚举的打字稿子集

问题描述

在打字稿中,我有一个像

export enum CarBrands {
   Toyota = "TOYOTA"
   Ford = "FORD"
   .....
}

我想像这样创建这个枚举的一个子集,但似乎做不到

enum JapaneseCars {
    CarBrands.Toyota
}

或创建具有子集的对象

const JapaneseCars = {
    Carbrands.Toyota
}

无论如何我可以创建一个使用来自另一个现有枚举的值的对象或枚举?

我无法将 CarBrands 枚举更改为其他数据类型

标签: typescriptenums

解决方案


您可以创建一个typeconst组合,其行为类似于作为另一个枚举子集的枚举。

缺点:此解决方案强制您让任何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`
}

我制作了一个TypeScript Playground,显示所有这些代码并进行类型检查


推荐阅读