Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

javascript - "Use Strict" needed in a TypeScript file?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Updates

  • 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).

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...