javascript - 将 JavaScript 关联数组转换为 TypeScript

标签 javascript 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 的方式,所以如果可能的话,我想趁机将其更改为更好的东西,同时转换为 typescript 。

我的直觉告诉我,我应该有一个来自类的 MenuAction 实例的集合,但我不确定如何实现它然后使用它。

我应该完全省略类的使用,而只使用数组中的普通对象吗?

(了解这是 Angular 1.X View Controller 的代码可能会有所帮助)。

最佳答案

就打字而言,这是您可以做到的一种方法:

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 对此类设计选择非常不可知。

...如果您希望该类型可供类实现使用,则必须将其定义为接口(interface)。自定义类型 ( type alias ) 和接口(interface)之间确实没有其他区别。

interface Action {
    Title: string;
    Action: (cb: () => void) => void;
    HasPermission: boolean;
}

关于javascript - 将 JavaScript 关联数组转换为 TypeScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40074659/

相关文章:

javascript - 需要将 GridView 中的链接按钮分组到单个名称下。

javascript - 无法获得匹配的 typescript 类型

angular - 将电话号码与 Angular 管对齐

javascript - 将时间字符串 ("hours:minute") 转换为日期对象

javascript - return 关键字的行为很奇怪

javascript - 如何用 Angular 暂停 setInterval?

javascript - 在php中登录后不显示模态框

typescript - 有没有办法使用 npm 脚本来运行 tsc -watch && nodemon --watch?

angular - 在 Angular Typescript 库中使用 MomentJS 时出错

javascript - ngFor 输入互相复制值