Skip to content

Instantly share code, notes, and snippets.

@VladSez
Created July 10, 2022 16:22
Show Gist options
  • Save VladSez/31e4c2ecef14e842663e978a36a883ad to your computer and use it in GitHub Desktop.
Save VladSez/31e4c2ecef14e842663e978a36a883ad to your computer and use it in GitHub Desktop.
Basic permissions with TS
const userRoles = {
admin: ["create", "update", "delete", "view"],
user: ["update", "view"],
anonymous: ["view"],
} as const;
type UserRoles = typeof userRoles;
const canRolePerformAction = <TRole extends keyof UserRoles>(
role: TRole,
action: UserRoles[TRole][number],
): boolean => {
const arrOfMembers = userRoles[role];
return arrOfMembers.includes(action as any);
};
// Usage
canRolePerformAction("user", "update");
canRolePerformAction("anonymous", "view");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment