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.
Code
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: falseInside 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
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.