【问题标题】:Convert Code to Typescript - The Clean Way将代码转换为打字稿 - 干净的方式
【发布时间】: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;
  }

我的问题是:

  1. 是否有更短、更简洁的方法来执行此操作? (我无法摆脱 EVENT_TYPES 或 ALIAS_EVENT_TYPES) 去路
  2. 现在我有“let types : any = {};” -- 有没有更好的方法来指定类型是字典?或者可以吗?
  3. 函数的返回类型应该是什么?目的?

我想我的一般问题是 - 如何改进此代码?清理它和更好的打字稿?

【问题讨论】:

  • 当您不打算重新分配有问题的变量时,您几乎可以肯定总是使用constlet 可以看作是一个警告,您稍后将重新分配。
  • meal. : ‘lunch’ 这会导致语法错误。
  • 我不禁注意到您的“打字稿”根本没有任何类型,除了单个 any

标签: javascript typescript coding-style


【解决方案1】:

清理它并更好地打字?

使用字符串联合:

type EVENT_TYPES = 'coffee' | 'lunch';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-12
    • 2021-06-04
    • 2014-06-26
    • 1970-01-01
    • 2014-06-14
    • 1970-01-01
    • 2016-12-21
    • 2012-05-04
    相关资源
    最近更新 更多