MakeEnums
MakeEnum is a TypeScript utility for creating custom enums with metadata. It allows you to define a configuration object and get an "enhanced" enum with typed keys, raw values, and helper methods.
Usage
vue
<template>
<v-list-item v-for="(mode, i) in Modes.getAll()">
<v-list-item-title>
{{ mode.title }}
<v-icon :color="mode.color">
{{ mode.icon }}
</v-icon>
</v-list-item-title>
</v-list-item>
</template>
<script setup>
const Modes = makeEnum({
open: {
title: 'Open',
icon: 'mdi-check',
color: 'green'
},
close: {
title: 'Close',
icon: 'mdi-close',
color: 'red'
},
})
// Get all items as an array
console.log(Modes.getAll())
/*
[
{ title: 'Open', value: 'open', icon: 'mdi-check', color: 'green' },
{ title: 'Close', value: 'close', icon: 'mdi-close', color: 'red' }
]
*/
// Get a single item
console.log(Modes.get('open'))
// { title: 'Open', value: 'open', icon: 'mdi-check', color: 'green' }
// Get by value
console.log(Modes.getByValue('close'))
// { title: 'Close', value: 'close', icon: 'mdi-close', color: 'red' }
// Keys and Values
console.log(Modes.Keys)
// { open: 'open', close: 'close' }
console.log(Modes.Values)
/*
{
open: { title: 'Open', icon: 'mdi-check', color: 'green' },
close: { title: 'Close', icon: 'mdi-close', color: 'red' }
}
*/
</script>Type Signature
ts
function makeEnum<T extends EnumConfig>(
config: T
): {
Keys: Record<keyof T & string, keyof T & string>
Values: T
get: (key: keyof T & string) => EnumItem<T[keyof T & string]>
getAll: () => EnumItem<T[keyof T & string]>[]
getByValue: (value: keyof T & string) => EnumItem<T[keyof T & string]> | undefined
}Parameters
| Parameter | Type | Description |
|---|---|---|
config | T extends EnumConfig | The configuration object for the enum, mapping keys to metadata objects |
Return Value
| Property / Method | Type | Description |
|---|---|---|
Keys | Record<string, string> | Object mapping enum keys to themselves. Useful for type-safe references |
Values | Record<string, BaseEnumConfig> | The raw configuration object passed to makeEnum. Each key maps to its metadata |
get | (key: string) => EnumItem<T[key]> | Returns a single enum item with its value and metadata |
getAll | () => EnumItem<T[key]>[] | Returns all enum items as an array. Each item includes value and metadata |
getByValue | (value: string) => EnumItem<T[key]> | undefined | Returns a single enum item by its value, or undefined if not found |