【问题标题】:Annotating a function assigned to a variable in TypeScript and TSLint在 TypeScript 和 TSLint 中注释分配给变量的函数
【发布时间】:2016-09-19 09:00:43
【问题描述】:

我有这 3 个功能,除了一些非常小的差异之外,它们几乎相同:

function toInt1(x: string): number { return parseInt(x, 10); }

const toInt2 = function (x: string): number { return parseInt(x, 10); };

const toInt3 = (x: string): number => parseInt(x, 10);

现在我是 TypeScript 的新手,但在 JS 领域,我更喜欢第三种,因为它最简洁、限制性最强(没有 this,没有提升函数名)。

但是,当我将 tslint 与此规则一起使用时(表面上看起来很合理,但也许我错了……):

"typedef": [
  true,
  "call-signature",
  "parameter",
  "arrow-parameter",
  "property-declaration",
  "variable-declaration",
  "member-variable-declaration"
],

我收到关于 toInt2toInt3 的这些错误:

expected variable-declaration: 'toInt2' to have a typedef
expected variable-declaration: 'toInt3' to have a typedef

看来我可以通过复制所有类型来修复它:

const toInt2: (x: string) => number = function (x: string): number { return parseInt(x, 10); };
const toInt3: (x: string) => number = (x: string): number => parseInt(x, 10);

但是,这非常冗长且没有吸引力。这真的是最好的做事方式吗?

【问题讨论】:

    标签: typescript tslint


    【解决方案1】:

    转译器想要为每个名称(变量)分配一个类型。一般来说,它可以从赋值中找出(推断)这种类型:

    // const x: number = 10;
    const x = 10; 
    // const y: string = 'foo';
    const y = 'foo';
    // const z: (a: string) => number = (a: string) => parseInt(a);
    const z = (a: string) => parseInt(a);
    

    这条规则'variable-declaration' 确保您不会让转译器推断类型,而是明确地为任何varletconst 声明编写类型签名(据我所知在文档中)。这可以提高可读性(您的代码的读者无需进一步调查就知道每个变量的静态类型),但代价是为所有变量编写类型签名。

    现在要解决这个问题,您有两个选择:

    1. 在适当的地方禁用规则inline
    2. 为此写custom rule

    【讨论】:

      猜你喜欢
      • 2018-03-04
      • 1970-01-01
      • 1970-01-01
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多