18

Just curious whether there are any drawbacks to including:

"compilerOptions": {
  "alwaysStrict": true,
 ...
 }

Since it's false by default. Thoughts?

Ole
  • 41,793
  • 59
  • 191
  • 359
  • 1
    It will `"Parse in strict mode and emit "use strict" for each source file"`, so your question is basically not different than: http://stackoverflow.com/questions/1335851/what-does-use-strict-do-in-javascript-and-what-is-the-reasoning-behind-it – Nitzan Tomer May 02 '17 at 00:11

2 Answers2

19

strict vs alwaysStrict

It is a good idea to not only include alwaysStrict, but to include the strict flag that enables alwaysStrict and also noImplicitAny, noImplicitThis, strictBindCallApply, strictNullChecks, strictFunctionTypes, strictPropertyInitialization and useUnknownInCatchVariables which are even more important.

Confusing names

There is a confusion about names here, because "strict" can mean few things here. The strict TypeScript flag is a shortcut to enable multiple other flags mentioned above. The alwaysStrict TypeScript flag parses your files in parses in the JS strict mode (as opposed to the JS sloppy mode and emits 'use strict' in the output. Instead of using the alwaysStrict flag you could add "use strict"; to all of your files (the ES modules are strict by default).

Other strict flags

The other strict TypeScript flags are even more important, because they help you eliminate these errors:

The strictNullChecks is the most important one in this respect.

It is not enabled by default for backwards compatibility with old code that was written before the new way of checking null and undefined was added.

See this answer for more details:

Knu
  • 14,806
  • 5
  • 56
  • 89
rsp
  • 107,747
  • 29
  • 201
  • 177
  • This answer is outdated: as of TypeScript 4.3 in August 2021, the --strict flag enables all of these flags. See https://mariusschulz.com/blog/the-strict-compiler-option-in-typescript#strict-type-checking-options – sw1337 Nov 03 '22 at 22:51
9

Just curious whether there are any drawbacks to including

Even if your file is not going to be in strict mode, it will be treated like it is. e.g. you will not be allowed to create a function declaration inside a function body : Why TS complains with function declarations inside function body

Personally: Its a good idea to have it on. And an even better idea to always use JavaScript / TypeScript modules (which are in strict mode by default).

Community
  • 1
  • 1
basarat
  • 261,912
  • 58
  • 460
  • 511