TypeScript:如何创建键仅为FabPerms类静态成员的字典?
解决TypeScript中基于类静态成员构建字典类型的问题
你想要创建一个以FabPerms类的非下划线开头静态成员为键、FabPerm[]为值的字典,但当前类型定义存在两个核心问题:
- TypeScript的模板字符串模式(
_${string})在Omit中无法直接精准过滤静态成员键; - 初始赋值的空对象
{}不符合“所有键必须存在”的类型约束(除非将键设为可选)。
修正方案一:提取有效键类型+可选映射
class FabPerm { constructor(private name:string) { FabPerms._values.push(this); } } class FabPerms{ static _values: FabPerm[] = []; // 替换any为具体类型,提升类型安全性 static role1 = new FabPerm('role1'); static role2 = new FabPerm('role2'); static role3 = new FabPerm('role3'); } // 提取所有非下划线开头的静态成员键类型 type ValidFabPermKeys = Extract<keyof typeof FabPerms, Exclude<string, `_${string}`>>; // 定义可选键的字典类型,适配初始空对象 const permissions: { [K in ValidFabPermKeys]?: FabPerm[] } = {}; // 正常赋值测试 permissions.role1 = [FabPerms.role1]; permissions.role2 = [FabPerms.role2, FabPerms.role3];
修正方案二:映射类型直接过滤键
这种写法更直观,通过映射类型的as子句直接排除不需要的键:
// 定义必填键的字典类型 type RequiredPermissionsDict = { [K in keyof typeof FabPerms as K extends `_${string}` | 'prototype' ? never : K]: FabPerm[]; }; // 定义可选键的字典类型 type OptionalPermissionsDict = { [K in keyof typeof FabPerms as K extends `_${string}` | 'prototype' ? never : K]?: FabPerm[]; }; // 可选类型适配空对象 const permissions: OptionalPermissionsDict = {}; // 必填类型需初始化所有键 const requiredPermissions: RequiredPermissionsDict = { role1: [], role2: [], role3: [] };
关键说明
- 使用
Extract或映射类型的as子句,可以精准筛选出FabPerms中符合要求的静态成员键,排除_values和prototype; - 添加
?将键设为可选,解决初始空对象不符合类型约束的问题;如果业务要求所有键必须存在,直接使用必填类型并初始化对应值即可。
内容的提问来源于stack exchange,提问作者Regular Jo
相关产品推荐
相关产品推荐

