Comparing version 2.2.0 to 2.2.1
@@ -5,2 +5,8 @@ <!-- markdownlint-disable MD009 MD024 --> | ||
## 2.2.1 | ||
2025-2-10 | ||
- 📖 update docs | ||
## 2.2.0 | ||
@@ -7,0 +13,0 @@ |
{ | ||
"name": "enum-plus", | ||
"version": "2.2.0", | ||
"version": "2.2.1", | ||
"description": "A drop-in replacement library for enum, tiny and powerful, like native enum but much more than that", | ||
@@ -5,0 +5,0 @@ "keywords": [ |
150
README.md
@@ -68,3 +68,3 @@ <!-- markdownlint-disable MD009 --> | ||
#### Example 1: Basic usage, almost the same as native enum | ||
- ### Example 1: Basic usage, almost the same as native enum | ||
@@ -81,3 +81,3 @@ ```js | ||
#### Example 2: string value type | ||
- ### Example 2: string enum values | ||
@@ -94,3 +94,3 @@ ```js | ||
#### 👍👍 [Recommended] Example 3 (standard usage): With key, value, and display text | ||
- ### 👍👍 [Recommended] Example 3 (standard usage): with Key, Value, and Display text | ||
@@ -105,7 +105,9 @@ ```js | ||
Week.Monday; // 1 | ||
Week.label(1); // Monday (this is display text, not key) | ||
Week.label(1); // Monday (here is display text, not key) | ||
``` | ||
#### 👍 Example 4: Omit the value field, automatically degrade to use the key field | ||
- ### 👍 Example 4: omit the value field | ||
If the `value` is the same as the Key, you can consider omitting the `value` field and using the Key instead | ||
```js | ||
@@ -122,3 +124,3 @@ import { Enum } from 'enum-plus'; | ||
#### Example 5: Create an enum dynamically | ||
- ### Example 5: Create from dynamic array | ||
@@ -131,18 +133,12 @@ Sometimes we need to create an enum dynamically using data returned by an api, in this case, we can use an array to initialize the enum | ||
const petTypes = await getPetsData(); | ||
// [ { id: 1, code: 'dog', name: 'Dog' }, | ||
// { id: 2, code: 'cat', name: 'Cat' }, | ||
// { id: 3, code: 'rabbit', name: 'Rabbit' } ]; | ||
const PetTypes = Enum(petTypes, { | ||
getValue: 'id', | ||
getLabel: 'name', | ||
getKey: 'code', // Optional, if omitted, value is used as Key as fallback | ||
}); | ||
Week.items; // Output is: | ||
// [ { value: 1, label: 'Dog', key: 'dog' }, | ||
// { value: 2, label: 'Cat', key: 'cat' }, | ||
// { value: 3, label: 'Rabbit', key: 'rabbit' } ] | ||
// [ { value: 1, key: 'dog', label: 'Dog' }, | ||
// { value: 2, key: 'cat', label: 'Cat' }, | ||
// { value: 3, key: 'rabbit', label: 'Rabbit' } ]; | ||
const PetTypes = Enum(petTypes); | ||
``` | ||
#### Example 6: initialized from native enum (extend native enum with additional methods) | ||
For more advanced usages, please refer to the [Custom initialization options](#custom-initialization-options) section | ||
- ### Example 6: initialized from native enum (i.e. extend native enum with additional methods) | ||
```ts | ||
@@ -169,11 +165,11 @@ import { Enum } from 'enum-plus'; | ||
### Pick enum value | ||
### Pick an enum value | ||
`Enum.XXX` | ||
Like native `enum`, pick a value of an enum item from the enum type | ||
Like native `enum`, just pick an enum value | ||
```js | ||
Week.Sunday; // 0 | ||
Week.Monday; // 1 | ||
Week.Sunday; // 0 | ||
``` | ||
@@ -185,5 +181,5 @@ | ||
`{value, label, key, raw}[]` | ||
`{ value, label, key, raw }[]` | ||
Get a read-only array containing all enum items, which can be easily traversed. Since it conforms to the data specification of [AntDesign](https://github.com/ant-design/ant-design) components, it supports one-click conversion of enums into components such as dropdowns and checkboxes, with just a single line of code. For more details, please refer to the examples below. | ||
Get a read-only array containing all enum items, which can be easily traversed. Since it conforms to the data specification of [Ant Design](https://github.com/ant-design/ant-design) components, it supports one-click conversion of enums into components such as dropdowns and checkboxes, with just a single line of code. For more details, please refer to the examples below. | ||
@@ -202,3 +198,3 @@ --- | ||
<sup>**_[Function]_**</sup> `label(keyOrValue?: string | number): string | undefined` | ||
<sup>**_[Function]_**</sup> `label(keyOrValue?: string | number): string | undefined` | ||
@@ -209,3 +205,3 @@ Get the display text of an enum item based on a certain enum value or Key. If localization is setup, the localized text will be returned. | ||
Week.label(1); // Monday | ||
Week.label('Monday'); // Monday (this is label, not key) | ||
Week.label('Monday'); // Monday (here is label, not key) | ||
``` | ||
@@ -217,3 +213,3 @@ | ||
<sup>**_[Function]_**</sup> `key(value?: string | number): string | undefined` | ||
<sup>**_[Function]_**</sup> `key(value?: string | number): string | undefined` | ||
@@ -223,3 +219,3 @@ Get the Key of an enum item based on the enum value, if the Key is not found, return `undefined`. | ||
```js | ||
Week.key(1); // Monday (this is key, not label) | ||
Week.key(1); // Monday (here is key, not label) | ||
``` | ||
@@ -231,3 +227,3 @@ | ||
<sup>**_[Function]_**</sup> `has(keyOrValue?: string | number): boolean` | ||
<sup>**_[Function]_**</sup> `has(keyOrValue?: string | number): boolean` | ||
@@ -247,3 +243,3 @@ Determine whether a certain enum item (value or Key) exists | ||
<sup>**_[Function]_**</sup> `toSelect(config?: OptionsConfig): {value, label}[]` | ||
<sup>**_[Function]_**</sup> `toSelect(config?: OptionsConfig): {value, label}[]` | ||
@@ -256,3 +252,3 @@ `toSelect` is similar to `items`, both return an array containing all enum items. The difference is that the elements returned by `toSelect` only contain the `label` and `value` fields. At the same time, the `toSelect` method supports inserting a default element at the beginning of the array, which is generally used for the default option of components such as dropdowns, representing all, none, or unlimited, etc., of course, you can also customize this default option | ||
<sup>**_[Function]_**</sup> `toMenu(): { key, label }[]` | ||
<sup>**_[Function]_**</sup> `toMenu(): { key, label }[]` | ||
@@ -280,3 +276,3 @@ Generate an object array that can be bound to the `Menu`, `Dropdown` components of [Ant Design](https://ant.design/components/menu) | ||
<sup>**_[Function]_**</sup> `toFilter(): { text, value }[]` | ||
<sup>**_[Function]_**</sup> `toFilter(): { text, value }[]` | ||
@@ -298,3 +294,3 @@ Generate an array of filters that can be passed directly to the `Column.filters` of the [Ant Design](https://ant.design/components/table#table-demo-head) Table component as a list of filtered items for the column, displaying a dropdown filter box in the table header to filter table data | ||
<sup>**_[Function]_**</sup> `toValueMap(): Record<V, { text: string }>` | ||
<sup>**_[Function]_**</sup> `toValueMap(): Record<V, { text: string }>` | ||
@@ -316,5 +312,5 @@ Generate an enum collection object that conforms to the [Ant Design Pro](https://procomponents.ant.design/en-US/components/schema) specification, which can be passed to components like `ProFormField`, `ProTable` | ||
<sup>**_[Override^1]_**</sup> `raw(): Record<K, T[K]>` | ||
<sup>**_[Override^1]_**</sup> `raw(): Record<K, T[K]>` | ||
<br/> | ||
<sup>**_[Override^2]_**</sup> `raw(keyOrValue: V | K): T[K]` | ||
<sup>**_[Override^2]_**</sup> `raw(keyOrValue: V | K): T[K]` | ||
@@ -338,3 +334,3 @@ The first overload without parameters returns the initialization object of the enum collection, which is used to initialize the Enum original init object. | ||
### valueType <sup>**_[Type-ONLY]_**</sup> | ||
### valueType <sup>**_[Type-ONLY]_**</sup> | ||
@@ -351,7 +347,7 @@ `value1 | value2 | ...` | ||
> Note that this is only a TypeScript type, which can only be used to constrain types and cannot be called at runtime, calling at runtime will throw an exception | ||
> Note that here is only a TypeScript type, which can only be used to constrain types and cannot be called at runtime, calling at runtime will throw an exception | ||
--- | ||
### keyType <sup>**_[Type-ONLY]_**</sup> | ||
### keyType <sup>**_[Type-ONLY]_**</sup> | ||
@@ -368,7 +364,7 @@ `key1 | key2 | ...` | ||
> Note that this is only a TypeScript type, which can only be used to constrain types and cannot be called at runtime, calling at runtime will throw an exception | ||
> Note that here is only a TypeScript type, which can only be used to constrain types and cannot be called at runtime, calling at runtime will throw an exception | ||
--- | ||
### rawType <sup>**_[Type-ONLY]_**</sup> | ||
### rawType <sup>**_[Type-ONLY]_**</sup> | ||
@@ -379,3 +375,3 @@ `{ value: V, label: string, [...] }` | ||
> Note that this is only a TypeScript type, which can only be used to constrain types and cannot be called at runtime, calling at runtime will throw an exception | ||
> Note that here is only a TypeScript type, which can only be used to constrain types and cannot be called at runtime, calling at runtime will throw an exception | ||
@@ -394,4 +390,4 @@ --- | ||
Week.Sunday; // 0 | ||
Week.Monday; // 1 | ||
Week.Sunday; // 0 | ||
``` | ||
@@ -420,3 +416,3 @@ | ||
> In the above example, the interpretation of Http status is referenced from [MDN](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Status) | ||
> The interpretation of Http status is referenced from [MDN](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Status) | ||
@@ -494,4 +490,4 @@ --- | ||
```js | ||
Week.key(1); // 'Monday', this is label, not key | ||
Week.key(Week.Monday); // 'Monday', this is label, not key | ||
Week.key(1); // 'Monday', here is label, not key | ||
Week.key(Week.Monday); // 'Monday', here is label, not key | ||
Week.key(9); // undefined, because it does not exist | ||
@@ -502,3 +498,3 @@ ``` | ||
#### Extend custom fields, unlimited | ||
#### Extend custom fields with unlimited numbers | ||
@@ -655,5 +651,5 @@ ```js | ||
#### Narrowing data types with enum value sequences <sup>_[TypeScript ONLY]_</sup> | ||
#### Narrowing the `number` type to enum value sequences <sup>_[TypeScript ONLY]_</sup> | ||
By using the `valueType` type constraint, you can narrow the field type from the broad `number` or `string` type to a limited sequence of enum values, which not only reduces the possibility of erroneous assignments, but also improves the readability of the code. | ||
By using the `valueType` type constraint, you can narrow the field type from the broad `number` or `string` type to a limited sequence of enum values, which not only reduces the possibility of erroneous assignments, but also improves the readability of the code | ||
@@ -664,11 +660,11 @@ ```typescript | ||
const goodWeekValue: typeof Week.valueType = 1; // ✅ Type correct, 1 is a valid week enum value | ||
const goodWeekName: typeof Week.keyType = 'Monday'; // ✅ Type correct, 'Monday' is a valid week enum name | ||
const badWeekValue: typeof Week.valueType = 8; // ❌ Type error, 8 is not a valid week enum value | ||
const badWeekName: typeof Week.keyType = 'Birthday'; // ❌ Type error, 'Birthday' is not a valid week enum name | ||
const goodWeekValue: typeof Week.valueType = 1; // ✅ Type correct, 1 is a valid week enum value | ||
const goodWeekName: typeof Week.keyType = 'Monday'; // ✅ Type correct, 'Monday' is a valid week enum name | ||
type FooProps = { | ||
value?: typeof Week.valueType; // 👍 Component property type constraint, prevent erroneous assignment, and also prompt which values are valid | ||
names?: (typeof Week.keyType)[]; // 👍 Component property type constraint, prevent erroneous assignment, and also prompt which values are valid | ||
value?: typeof Week.valueType; // 👍 Component property type constraint, prevent erroneous assignment, and also prompts which values are valid | ||
names?: (typeof Week.keyType)[]; // 👍 Component property type constraint, prevent erroneous assignment, and also prompts which values are valid | ||
}; | ||
@@ -679,2 +675,36 @@ ``` | ||
#### Custom initialization options | ||
In [Example 5: Create from dynamic array](#example-5-create-from-dynamic-array) section, we know that you can build an enum from dynamic data from the backend, but it is very likely that the field names of dynamic data are not `value`, `label`, `key`, but other field names. In this case, you can pass in a custom option to map these to other field names | ||
```js | ||
import { Enum } from 'enum-plus'; | ||
const petTypes = await getPetsData(); | ||
// [ { id: 1, code: 'dog', name: 'Dog' }, | ||
// { id: 2, code: 'cat', name: 'Cat' }, | ||
// { id: 3, code: 'rabbit', name: 'Rabbit' } ]; | ||
const PetTypes = Enum(petTypes, { | ||
getValue: 'id', | ||
getLabel: 'name', | ||
getKey: 'code', // getKey is optional | ||
}); | ||
Week.items; // Output is: | ||
// [ { value: 1, label: 'Dot', key: 'dog' }, | ||
// { value: 2, label: 'Cat', key: 'cat' }, | ||
// { value: 3, label: 'Rabbit', key: 'rabbit' } ] | ||
``` | ||
`getValue`, `getLabel`, `getKey` can also be a function to handle more complex business logic, for example: | ||
```js | ||
const PetTypes = Enum(petTypes, { | ||
getValue: (item) => item.id, | ||
getLabel: (item) => `${item.name} (${item.code})`, | ||
getKey: (item) => item.code, | ||
}); | ||
``` | ||
--- | ||
#### 😟 Naming conflict? | ||
@@ -803,6 +833,6 @@ | ||
Enum.extend({ | ||
getLabels(this: ReturnType<typeof Enum>) { | ||
return this.items.map((item) => item.label); | ||
toMySelect(this: ReturnType<typeof Enum>) { | ||
return this.items.map((item) => ({ value: item.value, title: item.label })); | ||
}, | ||
reversedValues(this: ReturnType<typeof Enum>) { | ||
reversedItems(this: ReturnType<typeof Enum>) { | ||
return this.items.reverse(); | ||
@@ -812,3 +842,3 @@ }, | ||
Week.getLabels(); // ['Sunday', 'Monday'] | ||
Week.toMySelect(); // [{ value: 0, title: 'Sunday' }, { value: 1, title: 'Monday' }] | ||
``` | ||
@@ -826,4 +856,4 @@ | ||
export interface EnumExtension<T, K, V> { | ||
getLabels: () => string[]; | ||
reversedValues: () => EnumItemClass<EnumItemInit<V>, K, V>[]; | ||
toMySelect: () => { value: V; title: string }[]; | ||
reversedItems: () => EnumItemClass<EnumItemInit<V>, K, V>[]; | ||
} | ||
@@ -841,2 +871,2 @@ } | ||
If you want to provide more friendly type hints in the extension methods, you may need to use these type parameters. These are all optional, if your extension method is as simple as `getLabels`, you can completely ignore them | ||
If you want to provide more friendly type hints in the extension methods, you may need to use these type parameters. However these are all optional, if you don't need them, you can omit them. |
@@ -68,3 +68,3 @@ <!-- markdownlint-disable MD009 MD001 --> | ||
#### 示例 1:基础用法,与原生枚举用法基本一致 | ||
- ### 示例 1:基础用法,与原生枚举用法基本一致 | ||
@@ -81,3 +81,3 @@ ```js | ||
#### 示例 2:值类型使用 string | ||
- ### 示例 2:值类型使用 string | ||
@@ -94,3 +94,3 @@ ```js | ||
#### 👍👍 【推荐】 示例 3(标准用法):包含 Key、Value,以及显示文本 | ||
- ### 👍👍 【推荐】 示例 3(标准用法):包含 Key、Value,以及显示文本 | ||
@@ -101,4 +101,4 @@ ```js | ||
const Week = Enum({ | ||
Sunday: { value: 0, label: '星期日' }, // 此示例不包含本地化 | ||
Monday: { value: 1, label: '星期一' }, // 此示例不包含本地化 | ||
Sunday: { value: 0, label: '星期日' }, // 此示例不考虑本地化 | ||
Monday: { value: 1, label: '星期一' }, // 此示例不考虑本地化 | ||
} as const); | ||
@@ -109,4 +109,6 @@ Week.Monday; // 1 | ||
#### 👍 示例 4:如果 Key 与 Value 相同,可以采用省略写法 | ||
- ### 👍 示例 4:省略 value 字段 | ||
如果 `value` 与 Key 相同,可以考虑省略 `value` 字段,使用 Key 作为枚举值 | ||
```js | ||
@@ -123,3 +125,3 @@ import { Enum } from 'enum-plus'; | ||
#### 示例 5:动态创建枚举 | ||
- ### 示例 5:动态数组构建枚举 | ||
@@ -132,18 +134,12 @@ 有时候我们需要使用接口返回的数据,动态创建一个枚举,这时可以采用数组的方式来初始化枚举 | ||
const petTypes = await getPetsData(); | ||
// [ { id: 1, code: 'dog', name: '狗' }, | ||
// { id: 2, code: 'cat', name: '猫' }, | ||
// { id: 3, code: 'rabbit', name: '兔子' } ]; | ||
const PetTypes = Enum(petTypes, { | ||
getValue: 'id', | ||
getLabel: 'name', | ||
getKey: 'code', // getKey可选,如果忽略则默认使用value作为Key | ||
}); | ||
Week.items; // 输出如下: | ||
// [ { value: 1, label: '狗', key: 'dog' }, | ||
// { value: 2, label: '猫', key: 'cat' }, | ||
// { value: 3, label: '兔子', key: 'rabbit' } ] | ||
// [ { value: 1, key: 'dog', label: '狗' }, | ||
// { value: 2, key: 'cat', label: '猫' }, | ||
// { value: 3, key: 'rabbit', label: '兔子' } ]; | ||
const PetTypes = Enum(petTypes); | ||
``` | ||
#### 示例 6:支持原生枚举初始化,相当于给原生枚举添加一些扩展方法 | ||
关于更高级的用法,请参考 [自定义初始化选项](#自定义初始化选项) 章节 | ||
- ### 示例 6:支持原生枚举初始化,相当于给原生枚举添加一些扩展方法 | ||
```ts | ||
@@ -174,7 +170,7 @@ import { Enum } from 'enum-plus'; | ||
像原生`enum`一样,从枚举类型中拾取一个枚举项的值 | ||
像原生`enum`一样,直接拾取一个枚举值 | ||
```js | ||
Week.Sunday; // 0 | ||
Week.Monday; // 1 | ||
Week.Sunday; // 0 | ||
``` | ||
@@ -186,3 +182,3 @@ | ||
`{value, label, key, raw}[]` | ||
`{ value, label, key, raw }[]` | ||
@@ -203,3 +199,3 @@ 获取一个包含全部枚举项的只读数组,可以方便地遍历枚举项。由于符合 [Ant Design](https://github.com/ant-design/ant-design) 组件的数据规范,因此支持将枚举一键转换成下拉框、复选框等组件,只需要一行代码,更多详情可以参考后面的例子 | ||
<sup>**_[方法]_**</sup> `label(keyOrValue?: string | number): string | undefined` | ||
<sup>**_[方法]_**</sup> `label(keyOrValue?: string | number): string | undefined` | ||
@@ -217,3 +213,3 @@ 根据某个枚举值或枚举 Key,获取该枚举项的显示文本。如果设置了本地化,则会返回本地化后的文本。 | ||
<sup>**_[方法]_**</sup> `key(value?: string | number): string | undefined` | ||
<sup>**_[方法]_**</sup> `key(value?: string | number): string | undefined` | ||
@@ -230,3 +226,3 @@ 根据枚举值获取该枚举项的 Key,如果不存在则返回`undefined` | ||
<sup>**_[方法]_**</sup> `has(keyOrValue?: string | number): boolean` | ||
<sup>**_[方法]_**</sup> `has(keyOrValue?: string | number): boolean` | ||
@@ -246,3 +242,3 @@ 判断某个枚举项(值或 Key)是否存在 | ||
<sup>**_[方法]_**</sup> `toSelect(config?: OptionsConfig): {value, label}[]` | ||
<sup>**_[方法]_**</sup> `toSelect(config?: OptionsConfig): {value, label}[]` | ||
@@ -255,3 +251,3 @@ `toSelect`与`items`相似,都是返回一个包含全部枚举项的数组。区别是,`toSelect`返回的元素只包含`label`和`value`两个字段,同时,`toSelect`方法支持在数组头部插入一个默认元素,一般用于下拉框等组件的默认选项,表示全部、无值或不限等,当然你也能够自定义这个默认选项 | ||
<sup>**_[方法]_**</sup> `toMenu(): { key, label }[]` | ||
<sup>**_[方法]_**</sup> `toMenu(): { key, label }[]` | ||
@@ -279,3 +275,3 @@ 生成一个对象数组,可以绑定给 [Ant Design](https://ant-design.antgroup.com/components/menu-cn) 的`Menu`、`Dropdown`等组件 | ||
<sup>**_[方法]_**</sup> `toFilter(): { text, value }[]` | ||
<sup>**_[方法]_**</sup> `toFilter(): { text, value }[]` | ||
@@ -297,3 +293,3 @@ 生成一个对象数组,可以直接传递给 [Ant Design](https://ant-design.antgroup.com/components/table-cn#table-demo-head) Table 组件的列配置,在表头中显示一个下拉筛选框,用来过滤表格数据 | ||
<sup>**_[方法]_**</sup> `toValueMap(): Record<V, { text: string }>` | ||
<sup>**_[方法]_**</sup> `toValueMap(): Record<V, { text: string }>` | ||
@@ -315,5 +311,5 @@ 生成一个符合 [Ant Design Pro](https://procomponents.ant.design/components/schema#valueenum) 规范的枚举集合对象,可以传递给 `ProFormField`、`ProTable` 等组件。 | ||
<sup>**_[方法重载^1]_**</sup> `raw(): Record<K, T[K]>` | ||
<sup>**_[方法重载^1]_**</sup> `raw(): Record<K, T[K]>` | ||
<br/> | ||
<sup>**_[方法重载^2]_**</sup> `raw(keyOrValue: V | K): T[K]` | ||
<sup>**_[方法重载^2]_**</sup> `raw(keyOrValue: V | K): T[K]` | ||
@@ -337,3 +333,3 @@ 第一个无参数的重载,返回枚举集合的初始化对象,即用来初始化 Enum 原始 init 对象。 | ||
### valueType <sup>**_[Type-ONLY]_**</sup> | ||
### valueType <sup>**_[Type-ONLY]_**</sup> | ||
@@ -354,3 +350,3 @@ `value1 | value2 | ...` | ||
### keyType <sup>**_[Type-ONLY]_**</sup> | ||
### keyType <sup>**_[Type-ONLY]_**</sup> | ||
@@ -371,3 +367,3 @@ `key1 | key2 | ...` | ||
### rawType <sup>**_[Type-ONLY]_**</sup> | ||
### rawType <sup>**_[Type-ONLY]_**</sup> | ||
@@ -392,4 +388,4 @@ `{ value: V, label: string, [...] }` | ||
Week.Sunday; // 0 | ||
Week.Monday; // 1 | ||
Week.Sunday; // 0 | ||
``` | ||
@@ -418,3 +414,3 @@ | ||
> 上面的代码示例中,Http 状态码的释义内容参考自 [MDN](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Status) | ||
> Http 状态码的释义内容参考自 [MDN](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Status) | ||
@@ -651,5 +647,5 @@ --- | ||
#### 使用枚举值序列来缩小数据类型 <sup>_[TypeScript ONLY]_</sup> | ||
#### 使用枚举值序列来缩小`number`类型 <sup>_[TypeScript ONLY]_</sup> | ||
使用 `valueType` 类型约束,可以将字段类型从宽泛的`number`或`string`类型缩小为有限的枚举值序列,这不但能减少错误赋值的可能性,还能提高代码的可读性。 | ||
使用 `valueType` 类型约束,可以将数据类型从宽泛的`number`或`string`类型缩小为有限的枚举值序列,这不但能减少错误赋值的可能性,还能提高代码的可读性 | ||
@@ -660,8 +656,8 @@ ```typescript | ||
const goodWeekValue: typeof Week.valueType = 1; // ✅ 类型正确,1 是一个有效的周枚举值 | ||
const goodWeekName: typeof Week.keyType = 'Monday'; // ✅ 类型正确,'Monday' 是一个有效的周枚举名 | ||
const badWeekValue: typeof Week.valueType = 8; // ❌ 类型错误,8 不是一个有效的周枚举值 | ||
const badWeekName: typeof Week.keyType = 'Birthday'; // ❌ 类型错误,'Birthday' 不是一个有效的周枚举名 | ||
const goodWeekValue: typeof Week.valueType = 1; // ✅ 类型正确,1 是一个有效的周枚举值 | ||
const goodWeekName: typeof Week.keyType = 'Monday'; // ✅ 类型正确,'Monday' 是一个有效的周枚举名 | ||
type FooProps = { | ||
@@ -675,2 +671,36 @@ value?: typeof Week.valueType; // 👍 组件属性类型约束,可以防止错误赋值,还能智能提示有效值有哪些 | ||
#### 自定义初始化选项 | ||
在 [示例 5:动态数组构建枚举](#示例-5动态数组构建枚举) 章节中,介绍了可以通过后端动态数据来构建枚举,但是很可能动态数据的字段名并不是`value`、`label`、`key`,而是其它的字段名。这时你可以传入一个自定义选项,把这些映射到其它字段名上 | ||
```js | ||
import { Enum } from 'enum-plus'; | ||
const petTypes = await getPetsData(); | ||
// [ { id: 1, code: 'dog', name: '狗' }, | ||
// { id: 2, code: 'cat', name: '猫' }, | ||
// { id: 3, code: 'rabbit', name: '兔子' } ]; | ||
const PetTypes = Enum(petTypes, { | ||
getValue: 'id', | ||
getLabel: 'name', | ||
getKey: 'code', // getKey可选 | ||
}); | ||
Week.items; // 输出如下: | ||
// [ { value: 1, label: '狗', key: 'dog' }, | ||
// { value: 2, label: '猫', key: 'cat' }, | ||
// { value: 3, label: '兔子', key: 'rabbit' } ] | ||
``` | ||
在上面的例子中,`getValue`、`getLabel`、`getKey` 还可以是一个函数,用来处理更复杂的业务逻辑,比如: | ||
```js | ||
const PetTypes = Enum(petTypes, { | ||
getValue: (item) => item.id, | ||
getLabel: (item) => `${item.name} (${item.code})`, | ||
getKey: (item) => item.code, | ||
}); | ||
``` | ||
--- | ||
#### 😟 命名冲突? | ||
@@ -799,6 +829,6 @@ | ||
Enum.extend({ | ||
getLabels(this: ReturnType<typeof Enum>) { | ||
return this.items.map((item) => item.label); | ||
toMySelect(this: ReturnType<typeof Enum>) { | ||
return this.items.map((item) => ({ value: item.value, title: item.label })); | ||
}, | ||
reversedValues(this: ReturnType<typeof Enum>) { | ||
reversedItems(this: ReturnType<typeof Enum>) { | ||
return this.items.reverse(); | ||
@@ -808,3 +838,3 @@ }, | ||
Week.getLabels(); // ['星期日', '星期一'] | ||
Week.toMySelect(); // [{ value: 0, title: '星期日' }, { value: 1, title: '星期一' }] | ||
``` | ||
@@ -822,4 +852,4 @@ | ||
export interface EnumExtension<T, K, V> { | ||
getLabels: () => string[]; | ||
reversedValues: () => EnumItemClass<EnumItemInit<V>, K, V>[]; | ||
toMySelect: () => { value: V; title: string }[]; | ||
reversedItems: () => EnumItemClass<EnumItemInit<V>, K, V>[]; | ||
} | ||
@@ -837,2 +867,2 @@ } | ||
如果你希望在扩展方法中提供更友好的类型提示,你或许可能需要使用到这些类型参数。这些都是可选的,如果你的扩展方法像`getLabels`这样简单,那么你完全可以忽略它们 | ||
如果你希望在扩展方法中提供更友好的类型提示,你或许可能需要使用到这些类型参数,但这些都是可选的,如果你不需要,可以直接省略掉它们 |
AI-detected possible typosquat
Supply chain riskAI has identified this package as a potential typosquat of a more popular package. This suggests that the package may be intentionally mimicking another package's name, description, or other metadata.
Found 1 instance in 1 package
181867
840
1