Javascript TypeScript 文件中需要“使用严格”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31391760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"Use Strict" needed in a TypeScript file?
提问by DeborahK
I've seen posts regarding where to put the "use strict" line in a TypeScript code file. My question is, why have it at all?
我看过有关在 TypeScript 代码文件中放置“use strict”行的位置的帖子。我的问题是,为什么要拥有它?
Since TypeScript is already a strongly typed language, what does "use strict" add?
既然 TypeScript 已经是强类型语言,那么“use strict”又增加了什么?
采纳答案by David Sherret
Updates
更新
- TypeScript 1.8+:
"use strict";is emitted in modules (Read more). - TypeScript 2.1+:
--alwaysStrictcompiler option parses all files in strict mode and emits"use strict"at the top of all outputted files (Read more).
- TypeScript 1.8+:
"use strict";在模块中发出(阅读更多)。 - TypeScript 2.1+:
--alwaysStrict编译器选项以严格模式解析所有文件,并"use strict"在所有输出文件的顶部发出(阅读更多)。
You can find a list of some examples by searching TypeScript's tests for "in strict mode".
您可以通过在 TypeScript 的“严格模式”测试中搜索一些示例列表。
Here's some examples of code that will only throw a compile time error when you "use strict";:
以下是一些代码示例,它们只会在您执行"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;
There are a few more examples where "use strict";would throw an error only at runtime. For example:
还有一些示例"use strict";只会在运行时抛出错误。例如:
"use strict";
delete Object.prototype;
Personally, I don't find it all that useful at preventing me from making mistakes in TypeScript and the additional noise it adds to a file makes me not bother writing it. That said, starting in TS 2.1 I'll enable the --alwaysStrictcompiler option because it adds the slight additional strictness without any code maintenance overhead.
就我个人而言,我认为它对于防止我在 TypeScript 中犯错误并没有多大用处,而且它给文件增加的额外噪音让我懒得写它。也就是说,从 TS 2.1 开始,我将启用--alwaysStrict编译器选项,因为它增加了一些额外的严格性,而没有任何代码维护开销。
回答by Jeremy
For my money, yes, "use strict";should be included in TypeScript files.
对于我的钱,是的,"use strict";应该包含在 TypeScript 文件中。
Disregarding the compile timeeffects of "use strict";on Typescript, there is likely a runtimeimpact when the generated javascript is executed:
不考虑对 Typescript的编译时影响,执行生成的 javascript 时"use strict";可能会影响运行时:
MDN identifies performance improvementsin avoiding boxing
thisin function calls, and the removal of thefunction.callerandfunction.argumentsproperties.Jeff Walden of Mozilla has also hinted at opportunities for performance gains in this answer.

