假设我们有一个权限配置对象,每个键代表某个模块,值是该模块的权限标识:
const permissions = {
user: "read_user",
admin: "manage_all",
guest: "read_public"
} as const;
目标是通过这个配置对象,生成一个联合类型,表示系统中所有可能的权限:
type PermissionType = "read_user" | "manage_all" | "read_public";
示例代码
// 定义权限配置对象
const permissions = {
user: "read_user",
admin: "manage_all",
guest: "read_public"
} as const;
// 定义通用工具类型
type Values<T extends object> = T[keyof T];
// 提取权限类型(结合 typeof 和工具类型,提取 permissions 对象的值类型)
type PermissionType = Values<typeof permissions>;
// 测试使用
const examplePermission: PermissionType = "read_user"; // 正确
// const invalidPermission: PermissionType = "delete_user"; //报错:类型不匹配