防止在JavaScript/Typescript中输入转换

发布于 2025-02-08 10:46:44 字数 304 浏览 2 评论 0原文

我目前正在学习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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

じее 2025-02-15 10:46:45

不,打字稿中没有规则可以阻止您这样做;表达式int + str的结果是字符串

现在,如果您尝试将其分配给类型number的变量,那将失败:

let int: number = 42
let str: string = "69"

let result: number = int + str;
//  ^ error: Type 'string' is not assignable to type 'number'.(2322)

请注意,这与松散的键入无关;以这种方式,使用+时,许多强大的语言(例如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 is string.

Now, if you tried to assign that to a variable of type number, that would fail:

let int: number = 42
let str: string = "69"

let result: number = int + str;
//  ^ error: Type 'string' is not assignable to type 'number'.(2322)

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. :-) )

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文