TypeScript文件中需要"使用严格"吗?

Deb*_*ahK 110 javascript typescript

我看过有关在TypeScript代码文件中将"use strict"行放在何处的帖子.我的问题是,为什么要这样呢?

由于TypeScript已经是强类型语言,"use strict"添加了什么?

Dav*_*ret 95

更新

  • TypeScript 1.8+:"use strict";在模块中发出(阅读更多).
  • TypeScript 2.1+:--alwaysStrict编译器选项以严格模式解析所有文件,并"use strict"在所有输出文件的顶部发出(阅读更多).

您可以通过搜索TypeScript的"严格模式"测试找到一些示例列表.

下面是一些代码示例,它们只会在您执行"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;
Run Code Online (Sandbox Code Playgroud)

还有一些例子"use strict";只会在运行时抛出错误.例如:

"use strict";
delete Object.prototype;
Run Code Online (Sandbox Code Playgroud)

就个人而言,我发现在阻止我在TypeScript中犯错时并没有那么有用,而且它添加到文件中的额外噪音让我不用费心去写它.也就是说,从TS 2.1开始,我将启用--alwaysStrict编译器选项,因为它增加了一些额外的严格性而没有任何代码维护开销.


Jer*_*emy 13

我的钱,是的,"use strict";应该包含在TypeScript文件中.

忽略在Typescript上的编译时间效果,生成的javascript执行时"use strict";可能会对运行时产生影响:

  • MDN识别性能改进,避免this在函数调用中进行装箱,以及删除function.callerfunction.arguments属性.

  • Mozilla的Jeff Walden也暗示了在这个答案中获得业绩增长的机会.