0.0.1-beta.1 • Published 11 months ago

@kortin/enum v0.0.1-beta.1

Weekly downloads
-
License
MIT
Repository
-
Last release
11 months ago

Enum npm npm

集中式管理你的枚举声明

📦 Installation

npm i @kortin/enum --save

🍽️ Usage

  1. 创建枚举

注意:为了获得更好的 TS 类型推导,枚举值类型需要使用 as const 声明

import Enum from '@kortin/enum';

const JobRunStateEnum = Enum.create([
  { key: 'Pending', label: '待构建', value: '0', color: 'red' },
  { key: 'Queuing', label: '排队中', value: 1, color: 'green' },
  { key: 'Building', label: '构建中', value: 2, color: 'red' },
  { key: 'Succeed', label: '构建完成', value: 3, color: 'green' },
  { key: 'Failed', label: '构建失败', value: 4, color: 'red' },
  { key: 'Canceled', label: '被取消', value: 5, color: 'red' },
  { key: 'Published', label: '已发布', value: 6, color: 'green' },
] as const);

其中 key、label、value 是枚举值必须有的属性,其余属性都可以根据业务需求自行添加

  • key: 枚举值唯一标识,与 TypeScript 中声明 enum 左侧的 key 意义相同
  • label: 枚举值展示的名称
  • value: 枚举值对应的实际值

如果你已经有了类似格式的枚举数据,可以直接使用 toEnum 方法创建枚举

const jobRunState = [
  { key: 'Pending', label: '待构建', value: '0' },
  { key: 'Queuing', label: '排队中', value: 1 },
  { key: 'Building', label: '构建中', value: 2 },
  { key: 'Succeed', label: '构建完成', value: 3 },
  { key: 'Failed', label: '构建失败', value: 4 },
  { key: 'Canceled', label: '被取消', value: 5 },
  { key: 'Published', label: '已发布', value: 6 },
] as const;

const jobRunStateEnum = toEnum(jobRunState);
  1. 使用枚举值

直接使用值(value

console.log(JobRunStateEnum.Pending); // '0'

if (record.runState === JobRunStateEnum.Succeed) {
  console.log('构建成功'); // 构建成功
}

使用枚举中定义的其他属性

JobRunStateEnum.get('Building'); // // { key: 'Building', label: '构建中', value: 2, color: 'red' }
JobRunStateEnum.get('Building').color; // 'red'
  1. 使用枚举数组
JobRunStateEnum.toOptions(); // [{ key: 'Pending', label: '待构建', value: '0' }, ...]

使用 .toOptions() 方法得到原始的枚举定义数组,你可以直接使用该数组渲染你的枚举选择框,或其他可交互组件。

<a-select :options="JobRunStateEnum.toOptions()" />

❓ Why

为什么需要使用这个库?

0.0.1-beta.1

11 months ago