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.

TypescriptSecurity Boundaries

Code

snippet
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 0

A 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

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.