2017-06-29 104 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); 

對我來說這是一個錯誤,我希望他們儘快修復。