1
我正在寻找改进一些代码,我觉得是一个很好的代表使用类装饰器作为mixins与Typescript this问题正是我正在寻找,但与'不可能的解决方案“我开始黑客入侵。Typescript类装饰器作为Mixins
结果是这样工作的代码
declare type Constructor<T = {}> = new(...args: any[]) => T
//Permissions function runs when @Permissions is placed as a class decorator
export function Permissions<TBase extends Constructor>(Base:TBase) {
return class extends Base {
read: boolean = false;
edit: boolean = false;
admin: boolean = false;
constructor(...args: any[]) {
super(...args);
this.read = false;
this.edit = false;
this.admin = false;
}
isRead(): boolean {
return this.read;
}
isEdit(): boolean {
return this.edit;
}
isAdmin(): boolean {
return this.admin;
}
setRead(value: boolean): void {
this.read = value;
}
setEdit(value: boolean): void {
this.edit = value;
}
setAdmin(value: boolean): void {
this.read = value
this.edit = value
this.admin = value
}
}
}
// Interface to provide TypeScript types to the object Object
export interface IPermissions {
read: boolean;
edit: boolean;
admin: boolean;
constructor(...args: any[]);
isRead(): boolean;
isEdit(): boolean;
isAdmin(): boolean
setRead(value: boolean): void
setEdit(value: boolean): void
setAdmin(value: boolean): void
}
//Extends the User Object with properties and methods for Permissions
interface User extends IPermissions {}
//Class Decorator
@Permissions
class User {
name: string;
constructor(name: string, ...args: any[]) {
this.name = name;
}
}
// Example instantiation.
let user = new User("Nic")
user.setAdmin(true);
console.log(user.name + ": has these Permissions; Read: " + user.isRead() + " Edit: " + user.isEdit() + " Admin: " + user.isAdmin())
,我有与界面做的问题。我想从权限功能动态地创建接口定义。所以我真正需要做的就是修改权限函数,以便在用户对象中获得正确的类型。
有没有办法在TypeScript中做到这一点?