Record Maps Role Unions To Capability Lists

A Record keyed by the Role union forces every role to declare its capabilities, so adding a role without a permission list fails to compile.

TypescriptSecurity Boundaries

Code

typescriptsnippet
25 lines
type Role = "admin" | "editor" | "viewer";

// role -> capability list keyed by the Role union itself
const CAPABILITIES: Record<Role, readonly string[]> = {
  admin: ["read", "write", "delete", "manage-users"],
  editor: ["read", "write"],
  viewer: ["read"],
};

// keyof Record<Role, ...> is exactly Role; add a role and this breaks until you fill it in
function can(role: Role, action: string): boolean {
  return CAPABILITIES[role].includes(action);
}

// user objects carry a role field typed to the same union
type User = { name: string; role: Role };

const users: User[] = [
  { name: "ada", role: "admin" },
  { name: "linus", role: "viewer" },
];

for (const user of users) {
  console.log(user.name, "delete:", can(user.role, "delete"), "write:", can(user.role, "write"));
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

ada delete: true write: true
linus delete: false write: false

Inside the snippet

Structurally, expect the function can and nothing else.

One loop does the cycling here: for (const user of users).

What to watch for

  • Nothing third-party is pulled in; the snippet is dependency-free.

Putting it to use

Entry signature: function can(role: Role, action: string)

Core lines

return CAPABILITIES[role].includes(action);

Interactive Tools for This Topic

FAQ

Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library. The file defines `can` at load time.