我正在尝试创建子类来处理应用程序不同区域的权限。每个子类都有一个不同的有效操作列表,以及我们在不允许操作时显示的各种原因。我正在尝试在父类上定义hasPermissions
方法以检查是否启用了权限,但是如果我传入的字符串不是当前实例的有效操作,我希望它抱怨。
我知道我可以通过在每个子类上定义hasPermissions
来处理这个问题,即hasPermissions (actionName: UserActions) { ... }
,但我希望避免这种情况。有没有一种方法,父类可以根据当前实例确定允许哪些操作?
declare var _;
type TPermission<TAction, TReason> = {
action: TAction;
enabled: boolean;
reason?: TReason;
}
class Permissions {
constructor(protected permissions) {
}
hasPermission(actionName) {
let permission = _.find(this.permissions, {
action: actionName
});
return permission ? permission.enabled : false;
}
}
type AdminActions = 'Add User' | 'Delete User';
type AdminReasons = 'MaxUsersReached' | 'CantDeleteAnotherAdmin';
type TAdminPermission = TPermission<AdminActions, AdminReasons>;
class AdminPermissions extends Permissions {
protected permissions: TAdminPermission[];
constructor(permissions: TAdminPermission[]) {
super(permissions);
}
}
type UserActions = 'Subscribe' | 'Unsubscribe';
type UserReasons = 'AlreadySubscribed' | 'AlreadyUnsubscribed';
type TUserPermission = TPermission<UserActions, UserReasons>;
class UserPermissions extends Permissions {
protected permissions: TUserPermission[];
constructor(permissions: TUserPermission[]) {
super(permissions);
}
}
let permissions: TUserPermission[] = [
{
action: 'Subscribe',
enabled: true
}
];
let user = new UserPermissions(permissions);
user.hasPermission('Subscribe'); // Valid, should return true
user.hasPermission('Unsubscribe'); // Valid, should return false
user.hasPermission('Add User'); // Invalid permission for UserPermissions, should error
答案 0 :(得分:2)
您可以将父类设为通用:
$ perl -0777 -lne 'while (/^(ltm pool pool_[\d._]+)(.*?)(?=^\})/gms){
$m=$1; $t=$2;
print "$m\n" if ($t =~ /address 10\.1\.104\.164/)}' file
ltm pool pool_10.1.105.30_80
ltm pool pool_10.1.105.31_80
然后:
class Permissions<T extends string> {
...
hasPermission(actionName: T) {
...
}
}
然后编译器会抱怨这个:
class AdminPermissions extends Permissions<AdminActions> { ... }
class UserPermissions extends Permissions<UserActions> { ... }
话说:
类型的参数&#39;&#34;添加用户&#34;&#39;不能分配给类型的参数 &#39; UserActions&#39;
如你所愿。