Is there a way to retrieve all values of an Enum (specified as a parameter or generic) and return them in a list? Additionally, if the user has a specific role, I only need to retrieve certain Enum values provided as a parameter.
I had the idea of grouping the two parameters as a tuple since they are either both given or neither at all.
My initial implementation would be something like this:
getItemsBasedOnRole<T extends { [s: number]: string }>(...[role, items]?: [UserRole, T[]]) : string[]
{
const allValues = Object.values(T);
if (role && items) // if tuple parameter exists
if (this.securityService.getUser.role === role)
return items;
return allValues;
}
const result = getItemsBasedOnRole<MyEnum>([ClientRole], [MyEnum.Value1, MyEnum.Value3]);
// returns [MyEnum.Value1, MyEnum.Value3]
const result = getItemsBasedOnRole<MyEnum>();
// returns [MyEnum.Value1, MyEnum.Value2, MyEnum.Value3]
export enum MyEnum{
Value1 = 'Value1',
Value2 = 'Value2',
Value3 = 'Value3',
}
There are some issues with Typescript:
T extends enum
is not valid.
Resolution: Replaced withT extends { [s: number]: string }
Object.values(T)
requires a value but T is a type.
I thought about adding a parameterenumValue: T
, but when calling the method, I couldn't pass justMyEnum
; it needed to beMyEnum.ValueX
.
No solution found for this yet.[role, items]?
optional tuple is not recognized.
No solution found for this issue either.
In my latest attempt, I tried to address the problems mentioned above:
getItemsBasedOnRole<T extends { [s: number]: string }>(enumValue: T, ...[role, items]: [UserRole, T[]]): string[]
The challenges I encountered mainly involve types and function definitions while my goal remains to create a dynamic list. Any suggestions or alternative approaches are welcome: whether that's splitting functions, utilizing parameters instead of generic types, etc.