“使用严格”在TypeScript文件中需要? [英] "Use Strict" needed in a TypeScript file?

查看:422
本文介绍了“使用严格”在TypeScript文件中需要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过关于在TypeScript代码文件中放置use strict行的位置的帖子。我的问题是,为什么要这样呢?

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 1.8+ :use strict; 在模块中发出(阅读更多内容)。

  • TypeScript 2.1+: - alwaysStrict 编译器选项以严格模式解析所有文件,并在所有输出文件的顶部发出use strict了解更多)。

  • TypeScript 1.8+: "use strict"; is emitted in modules (Read more).
  • 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).

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

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

这里有一些代码示例只会在use strict;

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;

还有一些例子use strict; 仅在运行时抛出错误。例如:

There are a few more examples where "use strict"; would throw an error only at runtime. For example:

"use strict";
delete Object.prototype;

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

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.

这篇关于“使用严格”在TypeScript文件中需要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆