Browse Source

chore: improve type for getDictOptions

main
刘凯 1 year ago
parent
commit
f0ef18f358
  1. 9
      src/types/utils.d.ts
  2. 11
      src/utils/dict.ts

9
src/types/utils.d.ts vendored

@ -3,3 +3,12 @@ import type { ComputedRef, Ref } from 'vue'
export type DynamicProps<T> = { export type DynamicProps<T> = {
[P in keyof T]: Ref<T[P]> | T[P] | ComputedRef<T[P]> [P in keyof T]: Ref<T[P]> | T[P] | ComputedRef<T[P]>
} }
type StringLiteralsToType<T extends 'string' | 'number' | 'boolean'>
= T extends 'string'
? string
: T extends 'number'
? number
: T extends 'boolean'
? boolean
: never

11
src/utils/dict.ts

@ -2,6 +2,7 @@
* *
*/ */
import { useDictStoreWithOut } from '@/store/modules/dict' import { useDictStoreWithOut } from '@/store/modules/dict'
import type { StringLiteralsToType } from '@/types/utils'
const dictStore = useDictStoreWithOut() const dictStore = useDictStoreWithOut()
@ -11,10 +12,10 @@ const dictStore = useDictStoreWithOut()
* @param dictType * @param dictType
* @returns {*|Array} * @returns {*|Array}
*/ */
export interface DictDataType { export interface DictDataType<T extends string | number | boolean = string> {
dictType: string dictType: string
label: string label: string
value: string | number | boolean value: T
key?: any key?: any
colorType: string colorType: string
cssClass: string cssClass: string
@ -39,8 +40,8 @@ export function getDictOpts(dictType: string) {
return getDictDatas(dictType) return getDictDatas(dictType)
} }
export function getDictOptions(dictType: string, valueType?: 'string' | 'number' | 'boolean'): any { export function getDictOptions<T extends 'string' | 'number' | 'boolean' = 'string'>(dictType: string, valueType?: T) {
const dictOption: DictDataType[] = [] const dictOption: DictDataType<StringLiteralsToType<T>>[] = []
const dictOptions: DictDataType[] = getDictDatas(dictType) const dictOptions: DictDataType[] = getDictDatas(dictType)
if (dictOptions && dictOptions.length > 0) { if (dictOptions && dictOptions.length > 0) {
dictOptions.forEach((dict: DictDataType) => { dictOptions.forEach((dict: DictDataType) => {
@ -53,7 +54,7 @@ export function getDictOptions(dictType: string, valueType?: 'string' | 'number'
: valueType === 'boolean' : valueType === 'boolean'
? `${dict.value}` === 'true' ? `${dict.value}` === 'true'
: Number.parseInt(`${dict.value}`), : Number.parseInt(`${dict.value}`),
}) } as DictDataType<StringLiteralsToType<T>>)
}) })
} }
return dictOption return dictOption