Is there a simpler way to streamline this code? It feels very repetitive and not quite right...
const FolderVisibility = new Enum<{
PUBLIC: 'public',
PRIVATE: 'private'
}>({
PUBLIC: 'public',
PRIVATE: 'private'
}) as Enum<{
PUBLIC: 'public',
PRIVATE: 'private'
}> & {
PUBLIC: 'public',
PRIVATE: 'private'
}
I'd like the IDE to indicate that the
FolderVisibility.PUBLIC == 'public'
since the parameter is readonly anyhow.
Here is the Enum
class, which has its own properties and a function
export default class Enum<T extends { [index: string]: string }> {
private readonly map: T;
public readonly values: (T[keyof T])[];
constructor(enums: T) {
Object.defineProperty(this, 'map', { value: {} });
for (let prop in enums) {
if (enums.hasOwnProperty(prop)) {
const value = enums[prop]
if(typeof value != 'string'){
throw new EnumError(value)
}
this.map[prop] = value
Object.defineProperty(this, prop, { value });
}
}
Object.defineProperty(this, 'values', { value: Object.values(this.map) });
}
isValid(text: any) {
if (!text) return true
return this.values.includes(text)
}
}
The idea is that by copying the object used in the constructor 4 times, it should indicate that FolderVisibility.values
is of type 'public' | 'private'
PS: I tried the following approach, but it returned string
for FolderVisibility.values
. It also feels quite lengthy.
const data = {
PUBLIC: 'public',
PRIVATE: 'private'
}
const FolderVisibility = new Enum<typeof data>(data) as Enum<typeof data> & typeof data