4

JavaScript 充满了像这样的警告:

const arr = [1, 2, 3]

for (const i in arr) {
  console.log(i + 1)
}

没有经验的 JS 开发人员预期的结果是1 2 3,但实际上是01 11 21.


看起来 TypeScript 默认情况下没有警告连接字符串和数字,有没有办法做到这一点?

更准确地说:我怎样才能收到有关案例的警告,例如'1' + 1

4

3 回答 3

3

TS Lint 可以防止使用for..in不当。https://palantir.github.io/tslint/rules/forin/

于 2019-08-05T20:39:36.457 回答
2

更新的有效答案 使用@typescript-eslint/restrict-plus-operands规则。两个操作数都必须是字符串或数字,但不能同时是两者:

来自https://github.com/typescript-eslint/typescript-eslint/tree/master/packages/eslint-plugin#usage的 eslint 配置

{
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "project": "./tsconfig.json"
  },
  "plugins": ["@typescript-eslint"],
  "rules": {
    "@typescript-eslint/restrict-plus-operands": "error"
  }
}

原来的

TS Lint 有“首选模板”规则,尽管我没有在这种情况下尝试过。它应该可以工作,因为 TypeScript 将i变量视为字符串类型。

https://palantir.github.io/tslint/rules/prefer-template/

此规则将要求您执行以下操作以使串联工作:

console.log(`${i}1`);

这至少应该向开发人员发出他们正在尝试执行连接的信号。

仅供参考,TS Lint 被弃用,取而代之的是 ES Lint,尽管我还没有将我的任何项目转移到该工具上。

更新的 ES Lint 具有相同的规则:https : //eslint.org/docs/rules/prefer-template

于 2019-08-05T20:55:10.470 回答
0

您正在连接数组属性名称,而不是它的值。这是因为for...in迭代对象的属性。我认为你想要做的是:

const arr = [1, 2, 3]

for (const i in arr) {
  console.log(arr[i] + 1)
}

您总是可以在其中编写一些代码来验证输入的类型,但首先了解for...in循环很重要 - 这是一些有关for...in使用数组的文档

您可以使用typeof在您的函数中进行简单的类型检查:

function doConcat(operand1, operand2) {
  if (typeof operand1 !== typeof operand2) { //simple typeof check
    console.log(`Cannot concat type: ${typeof operand1} with type: ${typeof operand2}`);
    return;
  }
  return operand1 + operand2;
}

const arr1 = [1, 2, 3]; //Should work - adding 2 numbers
for (const i in arr1) {
  console.log(doConcat(arr1[i], 1));
}

const arr2 = ['a', 'b', 'c']; //Should bomb - trying to concat number and string
for (const j in arr2) {
  doConcat(arr2[j], 1);
}

于 2019-08-05T21:01:41.493 回答