实现说明
全部逻辑都在函数 can中。
常见问题
运行前要先安装什么?
什么都不用额外装——运行时自带了代码所需的一切。 文件在加载时定义 can。
主要签名是 function can(role: Role)
核心语句
return role === "admin" ? "full access" : "read only";
代码示例
// interface:对象形状契约,支持 extends 继承扩展
interface Account {
id: string;
}
interface AccountWithMail extends Account {
email: string;
}
// type:union、原始值别名与交叉组合(compose)只有 type 能表达
type Role = "admin" | "viewer";
type Audit = Account & { lastSeen: number };
const user: AccountWithMail = { id: "u1", email: "[email protected]" };
const auditor: Audit = { id: "u2", lastSeen: 1731500000 };
function can(role: Role): string {
return role === "admin" ? "full access" : "read only";
}
console.log(`${user.id}: ${user.email}`);
console.log(`${auditor.id} lastSeen=${auditor.lastSeen}`);
console.log(can("admin"), can("viewer"));
// 同名 interface 会自动合并成员(declaration merging);type 重复声明则直接报错