我可以防止意外覆盖 TypeScript / JavaScript 中的局部变量吗?
Can I prevent accidental overwrite of local variables in TypeScript / JavaScript?
今天我浪费了一个小时来调试一个小问题,其中一个名为 server
的局部变量正在被初始化和配置 - 然后,在同一文件的最后一行中,不小心它被重新声明,例如通过另一个 var server = ...
语句,有效地创建了一个名为 server
的 new 变量,从而导致先前的变量超出范围;然而,因为这些是相同类型的变量,具有相同的名称,所以其他一切都继续工作,这使得调试变得相当困难。
是否有 TypeScript 或 JavaScript 语言功能可以防止此类事情发生?
我的想法是,在同一范围内声明两个具有相同名称的变量,根本不应该被允许。
也许有 linter 或一些质量保证工具能够检查和防止此类事情发生? (也许还有其他 "bad" 模式?)
尽可能使用let
。
一个let
变量不能在其声明之前使用:
var x = 3;
function f() {
console.log(x); // ReferenceError, x is not defined
let x = 5;
}
两个选项:
- 使用 ECMA 脚本 6 和
let
。
- 将 jslint 与
var
结合使用。
There is a closed issue about this on the GitHub/Microsoft/Typescript 页。建议以 ECMA Script 6 为目标并使用 let
.
ECMA 脚本 6 let
In ECMA Script 6 this would create an error:
let x = "foo";
let x = "bar"; // TypeScript with ECMA 6 will complain here
console.log(x);
Duplicate declaration, x
JSLint 与 var
此外,虽然以下不会抛出 TypeScript 错误,但 jslint 工具会报错,即使您没有使用 strict。
(function () {
var x, y;
x = "foo";
y = "foo";
function sayMsg() {
// jslint will complain here
var y = "bar";
}
sayMsg();
// jslint will also complain here
var x = "bar" + y;
}());
这就是 jslint 会告诉你的:
Redefinition of 'y' from line 3.
Combine this with the previous 'var' statement.
今天我浪费了一个小时来调试一个小问题,其中一个名为 server
的局部变量正在被初始化和配置 - 然后,在同一文件的最后一行中,不小心它被重新声明,例如通过另一个 var server = ...
语句,有效地创建了一个名为 server
的 new 变量,从而导致先前的变量超出范围;然而,因为这些是相同类型的变量,具有相同的名称,所以其他一切都继续工作,这使得调试变得相当困难。
是否有 TypeScript 或 JavaScript 语言功能可以防止此类事情发生?
我的想法是,在同一范围内声明两个具有相同名称的变量,根本不应该被允许。
也许有 linter 或一些质量保证工具能够检查和防止此类事情发生? (也许还有其他 "bad" 模式?)
尽可能使用let
。
一个let
变量不能在其声明之前使用:
var x = 3;
function f() {
console.log(x); // ReferenceError, x is not defined
let x = 5;
}
两个选项:
- 使用 ECMA 脚本 6 和
let
。 - 将 jslint 与
var
结合使用。
There is a closed issue about this on the GitHub/Microsoft/Typescript 页。建议以 ECMA Script 6 为目标并使用 let
.
ECMA 脚本 6 let
In ECMA Script 6 this would create an error:
let x = "foo";
let x = "bar"; // TypeScript with ECMA 6 will complain here
console.log(x);
Duplicate declaration, x
JSLint 与 var
此外,虽然以下不会抛出 TypeScript 错误,但 jslint 工具会报错,即使您没有使用 strict。
(function () {
var x, y;
x = "foo";
y = "foo";
function sayMsg() {
// jslint will complain here
var y = "bar";
}
sayMsg();
// jslint will also complain here
var x = "bar" + y;
}());
这就是 jslint 会告诉你的:
Redefinition of 'y' from line 3.
Combine this with the previous 'var' statement.