UNPKG

@cloudcome/utils-core

Version:
69 lines (68 loc) 2.76 kB
import { AnyObject, MergeIntersection, UnionToIntersection, UnionToTuple } from './types'; export type DictKey = string; export type DictValue = number | string; export type DictMetaAppend = { key?: string; value?: string | number; [key: string]: any; }; export type DictMeta<A extends DictMetaAppend> = A & { value: DictValue; }; export type DictDescription<A extends DictMetaAppend> = Record<DictKey, DictMeta<A>>; declare const dictError: unique symbol; type _CheckDefinition<O extends AnyObject> = { [K in keyof O & string]: K extends Capitalize<K> ? K extends `$${infer R}` ? O[K] & { [dictError]: `错误:枚举键名 ${K} 不能以 $ 符号开头`; } : O[K] : O[K] & { [dictError]: `错误:枚举键名 ${K} 必须以大写字母开头`; }; }; type _ToOriginDefProp<T extends AnyObject> = { [K in keyof T as `$${K & string}`]: MergeIntersection<T[K] & { readonly key: K; }>; }; type _KVRecord<T> = T extends Record<string, AnyObject> ? { readonly [K in keyof T]: T[K]['value']; } : never; type _VKRecord<T> = T extends Record<string, AnyObject> ? MergeIntersection<UnionToIntersection<{ [K in keyof T]: { [P in keyof T[K] as P extends 'value' ? T[K][P] & (string | number) : never]: K; }; }[keyof T]>> : never; export type DictExpose<A extends DictMetaAppend, E extends DictDescription<A>> = _ToOriginDefProp<E> & _KVRecord<E> & { readonly definition: E; readonly descriptions: MergeIntersection<A & { key: keyof E; }>[]; readonly keys: UnionToTuple<keyof E>; readonly length: UnionToTuple<keyof E>['length']; readonly values: UnionToTuple<E[keyof E]['value']>; readonly kvRecord: _KVRecord<E>; readonly vkRecord: _VKRecord<E>; toKeyRecord: <P extends keyof A>(prop: P) => Record<keyof E, A[P]>; toValRecord: <P extends keyof A>(prop: P) => Record<E[keyof E]['value'], A[P]>; }; /** * 声明一个枚举工厂函数 * @template A - 枚举元数据附加类型,扩展自 DictMetaAppend * @returns {Object} 返回包含 define 方法的对象 * * @property {function} define - 定义枚举的函数 * @template E - 枚举描述类型 * @param {_CheckDefinition<E>} definition - 枚举定义对象 * @returns {DictExpose<A, E>} 返回枚举的完整暴露对象 * @example * ```typescript * const createStatusDict = declareDict<{ label: string }>(); * const Status = createStatusDict.define({ * Pending: { value: 0, label: '待处理' }, * Approved: { value: 1, label: '已批准' } * }); * ``` */ export declare function declareDict<A extends DictMetaAppend>(): { define<const E extends DictDescription<A>>(definition: _CheckDefinition<E>): DictExpose<A, E>; }; export {};