What You'll Learn
You'll learn how the alwaysStrict compiler option ensures your compiled JavaScript always runs in strict mode and makes TypeScript parse your source files more rigorously.
What Is alwaysStrict?
The alwaysStrict compiler option does two things:
- Adds
"use strict";to the top of every emitted JavaScript file (unless your module format already implies strict mode) - Parses all TypeScript source files in strict mode during compilation
Think of it as putting safety rails on both your TypeScript code and the JavaScript that comes out the other end.
Why It Matters
JavaScript's strict mode catches common mistakes that would otherwise silently fail or cause weird behavior:
- Prevents accidental global variable creation from typos
- Disallows duplicate parameter names
- Throws errors on attempts to delete undeletable properties
- Restricts use of
withstatements - Makes
thissafer by preventing it from defaulting to the global object
When alwaysStrict is enabled, you get these protections automatically without manually writing "use strict"; in every file.
How It Works in TypeScript
By default, TypeScript modules already run in strict mode (ES modules are strict by default). But when you enable alwaysStrict:
- Non-module scripts get
"use strict";prepended - TypeScript's parser enforces strict mode syntax rules at compile time
- You catch strict-mode errors before runtime
This is particularly useful when working with script files (not modules) or when you want consistent strict behavior across all output formats.
When to Enable It
Enable alwaysStrict when you want guaranteed strict mode in all your JavaScript output. It's automatically enabled when you turn on the strict master flag, which you've already learned about.
Key Takeaway: The alwaysStrict option ensures both your TypeScript source and compiled JavaScript always follow strict mode rules, catching dangerous JavaScript patterns at compile time and runtime.