为什么 TypeScript 中的加法很奇怪?

Why is addition in TypeScript weird?

不知道为什么在TypeScript中添加using参数很奇怪

const getDir = (lastIndex: number) => {
// my other code
console.log(lastIndex + 10) // result is 1010
}

getDir(10);

结果显示 1010 而不是 20.

有人知道我做错了什么吗?

在 TypeScript 中指定 type 不处理转换 。你必须自己做。

在您的示例中,传递给 getDir 函数的参数是字符串而不是数字。

您在答案中发布的确切代码可以满足您的要求(生成 20)。你可以看看 here

如果您不处理转换,javascript 中的 string + string 将是串联而不是加法。

在 JavaScript 中有多种方法可以将字符串转换为数字。最简单的方法是在你的号码前加一个+。 (+'10' + 10)

示例:

console.log('Should be 20: ', 10 + 10)
console.log('Should be 1010: ', '10' + 10)
console.log('Should be 20: ', +'10' + 10)