防止在JavaScript/Typescript中输入转换
我目前正在学习JavaScript。我曾经使用静态类型的语言,因此自然而然地,我决定从打字稿而不是JS开始。打字稿很好,它解决了JS遇到的许多问题,但是这个“弱打字”确实触发了我。
我可以摆脱这一点并不是正确的:
let int: number = 42
let str: string = "69"
console.log(int + str)
有没有办法防止这种类型的转换即使在打字稿中也会发生?当将String
添加到Integer
时,我想获得错误。
I am currently learning JavaScript. I used to work with statically typed languages, so, naturally, I decided to start with TypeScript instead of JS. TypeScript is nice and it solves a lot of problems JS has, but this "weak typing" really triggers me.
It doesn't feel right that I can get away with this:
let int: number = 42
let str: string = "69"
console.log(int + str)
Is there a way to prevent this type of conversion from happening even in the TypeScript? I want to get an error when add string
to an integer
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,打字稿中没有规则可以阻止您这样做;表达式
int + str
的结果是字符串
。现在,如果您尝试将其分配给类型
number
的变量,那将失败:请注意,这与松散的键入无关;以这种方式,使用
+
时,许多强大的语言(例如Java和C#)做完全相同的事情,将数字隐含地转换为字符串。 java示例 | c#example 。理所当然的JavaScript走了很荒谬的,但这更多是关于语言的早期精神,而不是宁愿转换而不是投掷错误。 (不过,这两者都可能源于同一个基本目标,这是为了使语言真正适应  - 太多了,我们现在知道。:-))No, there's no rule in TypeScript that would prevent your doing that; the result of the expression
int + str
isstring
.Now, if you tried to assign that to a variable of type
number
, that would fail:Note that this has little to do with loose typing; many strongly-typed languages such as Java and C# do exactly the same thing, implicitly convert the number to a string when using
+
in that way. Java example | C# example. Granted JavaScript takes this ridiculously far, but that's more about the early ethos in the language having been to prefer conversion over throwing errors. (Both probably stem from the same underlying goal, though, which was to make the language really accommodating — too much so, we now know. :-) )如上所述,Typescript没有此功能,但Eslint确实可以: https://eslint.org /docs/rules/no-implitic-coercion 和 https://github.com/typescript-eslint/typescript-eslint-eslint/blob/main/main/packages/eslint-plugin/docs/rules/rules/rules/restrict-restrict-plus-operands- .md
Typescript as noted above doesn’t have this but Eslint does: https://eslint.org/docs/rules/no-implicit-coercion and https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/restrict-plus-operands.md