为什么 TypeScript 允许我添加字符串和数字?我可以预防吗? [英] Why TypeScript lets me add a string and a number? Can I prevent it?

查看:33
本文介绍了为什么 TypeScript 允许我添加字符串和数字?我可以预防吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码

let k = "1";
k += 1;
console.log(k);

使用 TypeScript 正确编译,即使在严格模式下.我原以为 tsc 会失败并出现一些错误,例如 Cannot add a string and an integer..为什么它构建成功?我可以防止这种危险行为吗?

compiles correctly using TypeScript, even in strict mode. I would have expected tsc to fail with some error like Cannot add a string and an integer.. Why does it build successfuly? Can I prevent this dangerous behavior?

推荐答案

它是有效的,因为它在 JS 中有效"在为什么某个操作不是类型错误的上下文中是一个非答案;参见 什么是所有合法的 JavaScript 都是合法的 TypeScript"?是什么意思?

"It's valid because it's valid in JS" is a non-answer in the context of why a certain operation isn't a type error; see What does "all legal JavaScript is legal TypeScript" mean?

在 JavaScript 中,像 alert("Your position in the queue is " + queuePos) 这样的代码是惯用的和常见的——通常写成 "str" + num.toString().

In JavaScript, code like alert("Your position in the queue is " + queuePos) is idiomatic and common -- it is not commonly written as "str" + num.toString().

TypeScript 的立场是惯用的 JS 不应该导致类型错误(在实际情况下).这意味着 string + number 是允许的强制转换.

TypeScript's position is that idiomatic JS should not cause type errors (when practical). This means that string + number is an allowed coercion.

+= 应该做什么的问题是在两个选项之间进行选择的问题:

The question of what += should do is then a matter of choosing between two options:

  • 一致性:x = x + y 应该与 x += y
  • 相同
  • 安全:x += y通常出现在stringnumber操作数,所以应该是非法强制
  • consistency: x = x + y should be identical to x += y
  • safety: x += y is not commonly done between string and number operands, so should be an illegal coercion

这两种选择都是明智的和有道理的;TypeScript 碰巧选择了第一个.

Both choices are sensible and defensible; TypeScript happened to choose the first.

这篇关于为什么 TypeScript 允许我添加字符串和数字?我可以预防吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆