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中做到這一點?