2017-06-29 77 views
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中做到这一点?

回答

0

tl; dr 作为写作可悲我不这么认为。

在我的util lib中,我遇到了一个Poolable mixin也实现了IPoolable的问题。

export function Poolable<T extends Constructor>(Base: T): T & ICtor<IPoolable> { 
    return class extends Base implements IPoolable { 
     public __pool__: Pool<this>; 
     public release() { 
      this.__pool__.release(this); 
     } 
     public initPool(pool: Pool<this>): void { 
      this.__pool__ = pool; 
     } 
     constructor(...args: any[]) { 
      super(...args); 
     } 
    }; 
} 

而且做混合舞蹈它的工作,通过接口沿。

class Base {} 
class Obj extends Poolable(Base) {} 
let pool = new Pool(Obj); 

但是下面的代码没有。

@Poolable 
class Base {} 
const pool = new Pool(Base); 

对我来说这是一个错误,我希望他们尽快修复。