【发布时间】:2018-06-18 00:28:15
【问题描述】:
我正在尝试将一些 JS 代码转换为打字稿(并在一般情况下对其进行清理)...
这是我目前拥有的:
const EVENT_TYPES = ['coffee', 'lunch', ''];
const ALIAS_EVENT_TYPES = {
cafe : 'coffee',
caffe : 'coffee',
meal. : ‘lunch’
};
let TYPES = createTypeDictionary();
function createTypeDictionary() {
let types : any = {};
_.each(EVENT_TYPES, function(type) {
if (type) {
types[type] = type;
}
});
_.each(ALIAS_EVENT_TYPES, function(type, index) {
types[index] = type;
});
return types;
}
我的问题是:
- 是否有更短、更简洁的方法来执行此操作? (我无法摆脱 EVENT_TYPES 或 ALIAS_EVENT_TYPES) 去路
- 现在我有“let types : any = {};” -- 有没有更好的方法来指定类型是字典?或者可以吗?
- 函数的返回类型应该是什么?目的?
我想我的一般问题是 - 如何改进此代码?清理它和更好的打字稿?
【问题讨论】:
-
当您不打算重新分配有问题的变量时,您几乎可以肯定总是使用
const。let可以看作是一个警告,您稍后将重新分配。 -
meal. : ‘lunch’这会导致语法错误。 -
我不禁注意到您的“打字稿”根本没有任何类型,除了单个
any。
标签: javascript typescript coding-style