热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

在打印文件中“使用严格”?-“UseStrict”neededinaTypeScriptfile?

IveseenpostsregardingwheretoputtheusestrictlineinaTypeScriptcodefile.Myquestion

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?

我看到过一些关于在打字稿代码文件中放置“使用严格”行的文章。我的问题是,为什么要拥有它?

Since TypeScript is already a strongly typed language, what does "use strict" add?

既然打字稿已经是强类型语言,那么“使用严格”添加什么呢?

2 个解决方案

#1


66  

Updates

更新

  • TypeScript 1.8+: "use strict"; is emitted in modules (Read more).
  • 打印稿1.8 +:“使用严格的”;在模块中释放(多读)。
  • TypeScript 2.1+: --alwaysStrict compiler option parses all files in strict mode and emits "use strict" at the top of all outputted files (Read more).
  • ——永远严格的编译器选项以严格的模式解析所有文件,并在所有输出文件的顶部发出“使用严格”(请参阅更多)。

You can find a list of some examples by searching TypeScript's tests for "in strict mode".

通过搜索“在严格模式下”的打字稿测试,您可以找到一些示例的列表。

Here's some examples of code that will only throw a compile time error when you "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";
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 --alwaysStrict compiler option because it adds the slight additional strictness without any code maintenance overhead.

就我个人而言,我觉得这并不能阻止我在打字稿中出错,而且它给文件添加的额外噪音让我懒得去写它。也就是说,从TS 2.1开始,我将启用——永远严格的编译器选项,因为它增加了一点额外的严格性,没有任何代码维护开销。

#2


9  

For my money, yes, "use strict"; should be included in TypeScript files.

对于我的钱,是的,“使用严格”;应该包含在打字稿文件中。

Disregarding the compile time effects of "use strict"; on Typescript, there is likely a runtime impact when the generated Javascript is executed:

不考虑“使用严格”的编译时间效应;在打字稿上,当生成的Javascript执行时,可能会有运行时的影响:

  • MDN identifies performance improvements in avoiding boxing this in function calls, and the removal of the function.caller and function.arguments properties.

    MDN识别性能改进,避免在函数调用中装箱,以及删除函数。调用者和功能。参数属性。

  • Jeff Walden of Mozilla has also hinted at opportunities for performance gains in this answer.

    Mozilla的Jeff Walden也暗示了在这个答案中性能的提升。


推荐阅读
author-avatar
l夜幕下的流星雨l
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有