Record Tables Guard Union Reads
A Record keyed by a role union forces every entry to exist, so reading table[role] never returns undefined and capability checks need no runtime fallback.
Code
type Role = 'viewer' | 'editor' | 'admin';
type Capabilities = Record<Role, readonly string[]>;
// 每个角色都必须给出能力表:漏键无法编译
const CAPABILITIES: Capabilities = {
viewer: ['read'],
editor: ['read', 'write'],
admin: ['read', 'write', 'delete'],
};
function can(role: Role, capability: string): boolean {
// table[role] 类型是 readonly string[] 而非 undefined:无兜底分支
return CAPABILITIES[role].includes(capability);
}
console.log(can('editor', 'write'), can('viewer', 'write'), can('admin', 'delete'));
// 新增角色先扩联合:编译器会指出 CAPABILITIES 缺了哪一行
type Audited = Role | 'auditor';
type NextTable = Record<Audited, readonly string[]>;
console.log(Object.keys(CAPABILITIES).join(','), Object.keys({} as NextTable).length);Output
Captured from a sandboxed run of this snippet in the build pipeline.
true false true
viewer,editor,admin 0A plain walkthrough of the logic
Everything happens inside the function can.
Caveats
- No dependencies section needed; the standard library is the whole story.
Using it
The primary signature is function can(role: Role, capability: string)
Key statements
return CAPABILITIES[role].includes(capability);
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
- Does the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared. The file defines `can` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.