TypeScript中使用instanceof判断类继承实现角色权限校验的问题
问题根因
你遇到的所有报错核心都是类型定义错误:你把「类本身的构造函数类型」和「类的实例类型」搞混了。你代码中getUserType返回的是类本身(可用于instanceof判断、可被new实例化),但你标注的返回类型UserType是类的实例类型,TypeScript 自然会认为它不符合构造函数、instanceof右值的要求。
具体解决方案
1. 修复基础类型定义
首先定义构造函数类型别名,用来标注「类本身」的类型:
abstract class UserType {} abstract class EmpRoleType extends UserType {} abstract class ClientRoleType extends UserType {} class EmpSupport extends EmpRoleType {} class ClientSupport extends ClientRoleType {} // 新增:代表UserType及其子类的构造函数类型 type UserTypeCtor = new (...args: any[]) => UserType;
2. 修复getUserType类型与权限校验函数
// 返回类型改为构造函数类型,而非实例类型 function getUserType(role: string): UserTypeCtor | null { switch(role) { case 'EmpSupport': return EmpSupport; case 'ClientSupport': return ClientSupport; default: return null; } } // 第一个参数是允许的父类构造函数,第二个参数是用户角色实例 function allowPermission(allowParentRole: UserTypeCtor, userRole: UserType) { return userRole instanceof allowParentRole; }
3. 修复实例化报错
实例化前先判断构造函数非空即可:
const RoleClass = getUserType('EmpSupport'); if (RoleClass) { const x = new RoleClass(); // 无类型报错 }
4. localStorage字符串映射实现
直接用映射表维护字符串和类的对应关系,比switch更易扩展:
// 定义字符串到类的映射表,类型安全 const ClassMap: Record<string, UserTypeCtor | undefined> = { EmpSupport, ClientSupport }; get UserType(): UserTypeCtor | null { const storageUserType = localStorage.getItem(AuthService.authStorageItems.userType); if (!storageUserType) { return null; } // 存在就返回对应类,不存在返回null,无需捕获异常 return ClassMap[storageUserType] ?? null; }
如果你的业务需要返回类的实例而非类本身,最后一步改为return ClassMap[storageUserType] ? new ClassMap[storageUserType]() : null即可。
内容的提问来源于stack exchange,提问作者JudasMoses
相关产品推荐
相关产品推荐

