typescript定义type为枚举类型的key值,枚举类型转对象数组
Author:zhoulujun Date:
遇到两个问题
类型取值限定为枚举类型的key
1,我需要某个数据类型限制为枚举类型的key,比如:
当然,你可以把枚举反过来写!但是那就更加离谱了
解决办法:
// 假设我一个枚举
enum ENUM_TYPE {
ALL = 'all',
SOME = 'some',
LITTLE = 'little'
}
// 获取枚举的 value
type IValue = `${ENUM_TYPE}` // 'all' | 'some' | 'little'
// 获取枚举的 key
type IKey = keyof typeof ENUM_TYPE // 'ALL' | 'SOME' | 'LITTLE'
推荐 keyof typeof ENUM_TYPE
keyof
keyof是ts的索引类型操作符,属于ts的高级类型。
对于任何类型T,keyof T得到的类型是T的属性名称字符串字面量类型构成的联合类型。
typeof
typeof 操作符可以用来获取一个变量或对象的类型。
typeof 和 keyof 操作符
typeof 操作符可以用来获取一个变量或对象的类型。而 keyof 操作符可以用于获取某种类型的所有键,其返回类型是联合类型。
const COLORS = {
red: 'red',
blue: 'blue'
}
// 首先通过typeof操作符获取Colors变量的类型,然后通过keyof操作符获取该类型的所有键,
// 即字符串字面量联合类型 'red' | 'blue'
type Colors = keyof typeof COLORS
let color: Colors;
是不是爽歪歪!
枚举类型转为对象数组
第二个问题,就是枚举变量对象,遍历出来,比如传给 radio checkbox select 组件。
const dataSourceTypeList = Object.keys(DatasourceTypeEnum)
.map(key => ({
text: DatasourceTypeEnum[key as keyof typeof DatasourceTypeEnum],
value: key,
}));
推荐方法:
function fromEnum<T extends Enum, C>(
enumSrc: T,
projection: (item: [keyof T, T[keyof T]], index: number, array: [keyof T, T[keyof T]][]) => C,
skip?: (value: [keyof T, T[keyof T]], index: number, array: [keyof T, T[keyof T]][]) => boolean
) {
let entries = enumToEntries(enumSrc);
if (skip) entries = entries.filter(skip);
return entries.map(projection);
}
枚举转对象
type EnumKeys<Enum> = Exclude<keyof Enum, number>
const enumObject = <Enum extends Record<string, number | string>>(e: Enum) => {
const copy = {...e} as { [K in EnumKeys<Enum>]: Enum[K] };
Object.values(e).forEach(value => typeof value === 'number' && delete copy[value]);
return copy;
};
const enumKeys = <Enum extends Record<string, number | string>>(e: Enum) => {
return Object.keys(enumObject(e)) as EnumKeys<Enum>[];
};
const enumValues = <Enum extends Record<string, number | string>>(e: Enum) => {
return [...new Set(Object.values(enumObject(e)))] as Enum[EnumKeys<Enum>][];
};
可以改为一个公用类,其是一般就是需要keys或者values而已。
export class EnumUtils { /**
* Returns the enum keys
* @param enumObj enum object
* @param enumType the enum type
*/
static getEnumKeys(enumObj: any, enumType: EnumType): any[] { return EnumUtils.getEnumValues(enumObj, enumType).map(value => enumObj[value]);
} /**
* Returns the enum values
* @param enumObj enum object
* @param enumType the enum type
*/
static getEnumValues(enumObj: any, enumType: EnumType): any[] { return Object.keys(enumObj).filter(key => typeof enumObj[key] === enumType);
}
}
获取枚举类型的键名
enum DatasourceTypeEnum {
bkbase,
local_db = '本地数据库直连',
cloud_db = '云数据库直连',
excel = 'Excel 导入',
jsonapi = 'REST API',
}
console.log(DatasourceTypeEnum[DatasourceTypeEnum.bkbase])//bkbase
console.log(DatasourceTypeEnum[DatasourceTypeEnum.local_db])//undefined
如果枚举没有给值,可以直接获取。赋值了,就是undefined ,那么通用方法是什么?
这里还发现一个问题:
enum ScreenType {
Edit = 1,
New = '222',
View = 4
}
var typeEdit : ScreenType = ScreenType.Edit;
var typeNew : ScreenType = ScreenType.New ;
console.log(ScreenType[typeEdit ]); //Edit
console.log(ScreenType[typeNew ]); //undefined
这个我么有知道好的方案?希望哪位大佬留言补充下
参考文章:
ts、typescript、enum、枚举、ts 获取枚举对应的类型、获取 enum 的 key 和 valuehttps://www.cnblogs.com/PeiQi1229/p/16512842.html
TypeScript typeof 操作符 www.semlinker.com/ts-typeof/
一文让你彻底掌握 TS 枚举 https://juejin.cn/post/6844904112669065224
用于 TypeScript 枚举的实用辅助函数 https://www.51cto.com/article/702545.html
转载本站文章《typescript定义type为枚举类型的key值,枚举类型转对象数组》,
请注明出处:https://www.zhoulujun.cn/html/webfront/ECMAScript/typescript/2023_0522_8952.html