我见过关于在TypeScript代码文件中放置“use strict”行的位置的帖子。我的问题是,为什么要这样呢?
由于TypeScript已经是强类型语言,“use strict”添加了什么?
答案 0 :(得分:85)
<强>更新强>
"use strict";
在模块(Read more)中发出。--alwaysStrict
编译器选项以严格模式解析所有文件,并在所有输出文件(Read more)的顶部发出"use strict"
。您可以通过在严格模式&#34;中搜索TypeScript&#34;的测试来找到一些示例的列表。
这里有一些代码示例,只会在您"use strict";
时抛出编译时错误:
// future reserved keyword not allowed as variable name
var let,
yield,
public,
private,
protected,
static,
implements;
// "delete" cannot be called on an identifier
var a;
delete a;
// octal literals not allowed
03;
还有一些例子"use strict";
仅在运行时抛出错误。例如:
"use strict";
delete Object.prototype;
就我个人而言,我没有发现阻止我在TypeScript中犯错的所有功能,以及它添加到文件中的额外噪音让我不用费心去写它。也就是说,从TS 2.1开始,我将启用--alwaysStrict
编译器选项,因为它增加了一些额外的严格性,而没有任何代码维护开销。
答案 1 :(得分:12)
我的钱,是,"use strict";
应该包含在TypeScript文件中。
忽略"use strict";
对Typescript的编译时效果,生成的javascript执行时可能会产生运行时影响:
MDN identifies performance improvements在函数调用中避免装箱this
,以及删除function.caller
和function.arguments
属性。
Mozilla的Jeff Walden也在this answer暗示了提升业绩的机会。