【发布时间】:2021-09-29 00:36:25
【问题描述】:
我有一个这样的类层次结构:
用户:
- 角色:角色[]
角色:
- 权限:权限
每个类都有一个构造函数,将 args 转换为其指定的类,例如 User 将角色转换为 Role 实例。 Role 将权限转换为 Permission 实例。
示例代码:
const user = new User({
roles: [
{role_name: 'admin', permissions: {'*': '*'}}
]
})
当我使用嵌套的权限对象为用户传递 JSON 时,我得到编译器错误,因为权限上有方法。 Property 'has' is missing in type '{ '*': string; }' but required in type 'Permission'.
如何避免这些问题?
编辑:
如何使 Roles 类接受作为对象的权限,以便它可以正确地将 JSON 强制转换为 Permission 类型?
// users.ts
export interface User extends BaseModel {
createdAt?: string;
updatedAt?: string;
email?: string;
username?: string;
fullname?: string;
microsoftId?: string;
roles?: UserRole[];
}
export class User {
constructor(props?: Partial<User>) {
if(!props){
props = {};
}
props.roles = props.roles?.map(role => new Role(role)) || [];
Object.assign(this, props);
}
hasPermission(service: string, perm: PermissionType){
for(let role of this.roles || []){
const has = (role.permissions as Permission).has(service, perm);
if(has){
return has;
}
}
return false;
}
}
// roles.ts
export interface Permission {
[key: string]: PermissionType[]|any;
}
export class Permission {
constructor(props: Partial<Permission>){
Object.assign(this, props);
}
has(service: keyof Permission, permName: PermissionType|undefined): boolean {
//.....
}
}
export interface Role extends BaseModel {
createdAt?: string;
updatedAt?: string;
role_name?: string;
description?: string;
scopes?: string[];
permissions: Permission;
}
export class Role {
constructor(props?: Partial<Role>) {
if(!props){
props = {};
}
props.permissions = new Permission(props.permissions || {});
if (!Array.isArray(props.scopes)) {
props.scopes = [];
}
Object.assign(this, props);
}
}
【问题讨论】:
-
您定义了一个类
Permission,它有一个has方法。您的{ "*": "*" }没有该方法,因此不是Permission。 -
嗨@SilvioMayolo - 我澄清了我的问题。我想在构造函数中允许普通对象 - 但将它们正确强制转换为正确的 Permission 类型。此数据源自服务器 REST 响应(作为 JSON),因此我需要强制它们添加/等方法。
-
然后当你收到 JSON 数据时,将其转换为 Permission 对象
标签: typescript