在 TypeScript 和 TSLint 中注释分配给变量的函数

Annotating a function assigned to a variable in TypeScript and TSLint

我有这 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);

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

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

// 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' 确保您不会让转译器推断类型,但您明确地为任何 varlet 或 [=14] 编写类型签名=] 声明(据我在文档中所见)。这可以提高可读性(代码的 reader 知道每个变量的静态类型而无需进一步调查),但是以编写所有变量的类型签名为代价。

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

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