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
之类的警告
答案 0 :(得分:3)
TS Lint可以防止不适当地使用for..in
。 https://palantir.github.io/tslint/rules/forin/
答案 1 :(得分: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
答案 2 :(得分:0)
您要串联数组的属性名,而不是它的值。这是因为for...in
迭代对象的属性。我想您要尝试的是这样:
const arr = [1, 2, 3]
for (const i in arr) {
console.log(arr[i] + 1)
}
您总是可以在其中编写一些代码来验证输入的类型,但是首先了解for...in
循环很重要-这里是一些documentation regarding for...in
use with arrays
您可以使用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);
}