[英]Converting javascript associative array to typescript
在我們的系統之一中,我們有很多與UI相關的javascript,它們可以處理菜單操作,如下所示
var menuActions = {
"edit-profile": {
Title: "rs_edit_profile",
Action: function(callback){
//some logic here to handle the UI
},
HasPermission: true
},
"delete-profile": {
Title: "rs_edit_profile",
Action: function(callback){
//some logic here to handle the UI
},
HasPermission: true
},
"create-profile": {
Title: "rs_edit_profile",
Action: function(callback){
//some logic here to handle the UI
},
HasPermission: false
}
}
和用於與switch
/ if
情況下,像if(menuAction[actionName] === "edit profile")...
然后調用menuActions[actionName].Action()
我們現在正在將系統轉換為TypeScript,這對我們來說是全新的,我一直在堅持最好的方式來重新組織和轉換這段特定的代碼。
我現在不喜歡使用javascript進行操作,因此,如果可能的話,我想借此機會將其更改為更好的字體,同時進行打字稿轉換。
我的直覺說我應該從一個類中收集MenuAction
實例,但是我不確定如何實現並使用它。
我是否應該完全省略類的使用,而只在數組中使用普通對象?
(這可能有助於知道這是Angular 1.X視圖控制器的代碼)。
就打字而言,這是您可以做到的一種方式:
type Action = {
Title: string;
Action: (cb: () => void) => void;
HasPermission: boolean;
}
var menuActions: {[key:string]: Action} = {
"edit-profile": {
Title: "rs_edit_profile",
Action: function (callback) {
//some logic here to handle the UI
},
HasPermission: true
},
"delete-profile": {
Title: "rs_edit_profile",
Action: function (callback) {
//some logic here to handle the UI
},
HasPermission: true
},
"create-profile": {
Title: "rs_edit_profile",
Action: function (callback) {
//some logic here to handle the UI
},
HasPermission: false
}
}
是否使用類實例取決於您,TS對於這樣的設計選擇是完全不可知的。
...,如果您希望該類型可用於類的implement
,則必須將其定義為接口。 自定義類型( 類型別名 )和接口之間確實沒有其他區別。
interface Action {
Title: string;
Action: (cb: () => void) => void;
HasPermission: boolean;
}
這樣的事情怎么樣:
class MenuAction {
private id: string;
private title: string;
private hasPermission: boolean;
private action: (cb: Function) => void;
constructor(id: string, title: string, hasPermission: boolean, action: (cb: Function) => void) {
this.id = id;
this.title = title;
this.hasPermission = hasPermission;
this.action = action;
}
get Title() {
return this.title;
}
get HasPermission() {
return this.hasPermission;
}
get Action() {
return this.action;
}
equals(id: string): boolean {
return this.id === id;
}
}
const actions = [
new MenuAction("edit-profile", "rs_edit_profile", true, function(callback) {
//some logic here to handle the UI
}),
new MenuAction("delete-profile", "rs_edit_profile", true, function(callback) {
//some logic here to handle the UI
}),
new MenuAction("create-profile", "rs_edit_profile", false, function(callback) {
//some logic here to handle the UI
})
];
function execute(id: string, callback: Function) {
actions.filter(action => action.equals(id)).forEach(action => {
action.Action(callback);
});
}
( 操場上的代碼 )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.