I have this constant declaration:
export const Actions = {
VIEW: 'view',
EDIT: 'edit',
};
and lets assume now I have a function like below:
// how to ensure action variable below is string of value either view or edit
function insertAction(action: string): void {
console.log('trust me i inserted the action');
}
My goal is to allow action parameter to have values only view | edit and understand this *dynamically, so please do not suggest using union solution because I know that already and is not fit to my purpose.
I have tried signature like the one below
function insertAction(action: typeof Actions[keyof typeof Actions]
but it does not work.
I can still call the function insertAction('whatever') and ts compile does not fail neither the linter.
In my package.json am using typescript version 4.4.2 with PHPStorm Editor and nextjs
"typescript": "^4.4.2"
typeof Actions[keyof typeof Actions]should work if you declareActionswith theas constmodifier. Eg:export const actions = {...} as const;. Can you let us know if that works?as consttypescript syntax was not aware of it. Withoutas constthis was not working. Also am open to any solution if there are more elegant ones although this achieves now what I intend to and am happy