← 中文资源

简体中文版本

Record 把角色联合映射成能力表

Record 以 Role 联合作键:每个角色都必须声明能力清单,漏一个键在编译期就报错,而不是运行时拿到 undefined 的权限。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

ada delete: true write: true
linus delete: false write: false

实现说明

逻辑集中在函数 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"));
}