实现说明
逻辑集中在函数 can里。
for (const user of users) 承担全部的逐项处理。
常见问题
这个示例需要哪些包?
一个都不用。代码用到的符号都在标准库里解析。 文件在加载时定义 can。
入口签名:function can(role: Role, action: string)
核心语句
return CAPABILITIES[role].includes(action);
代码示例
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"));
}