实现说明
函数 can定义了示例的全部动作。
常见问题
运行时需要 npm、pip、cargo 之类帮忙吗?
不需要——包管理器在这里无事可做,没有任何声明。 文件在加载时定义 can。
主要签名是 function can(role: Role, capability: string)
核心语句
return CAPABILITIES[role].includes(capability);
代码示例
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);