I am currently in the process of defining a new type based on an immutable object, like so:
const Actions = {
'user.crud': ['user.create', 'user.read', 'user.update', 'user.delete'],
} as const
type ActionsType = keyof typeof Actions | typeof Actions[keyof typeof Actions][number]
The aforementioned approach works effectively and establishes the ActionsType
with specific string literals ('user.crud', 'user.create', etc.).
Nevertheless, the simplicity of the Actions
object above does not meet my requirements. Ideally, I would like to dynamically generate the Actions using functions. After transitioning the above setup to be generated by a function:
// define a function to create all actions for a given role
function getActions(role: string): Record<string, string[]> {
return {
[`${role}.crud`]: [`${role}.create`, `${role}.read`, `${role}.update`, `${role}.delete`],
}
}
// generate the Actions using a function
const ActionsFromFunction = {
...getActions('user'),
} as const
// establish the Actions from an immutable object with values produced by getActions()
type ActionsFromFunctionType = keyof typeof ActionsFromFunction | typeof ActionsFromFunction[keyof typeof ActionsFromFunction][number]
the type ActionsFromFunctionType
no longer reflects the string literals but instead is set to: string | number
, causing type checks to fail as any string is accepted.
I have created a demonstration of the scenario:
Is there a method to construct the Actions
object through a function while preserving the specific string literals within the type?