TypeScript Reference ยท Keywords and Declarations
"use strict" in TypeScript
Reference for the "use strict" directive in TypeScript: ES modules, alwaysStrict, what strict mode changes at runtime and how it differs from the strict option.
"use strict" is a JavaScript directive: a string statement at the top of a script or function body that switches the code into strict mode. Strict mode turns silent mistakes into exceptions, forbids a few legacy features, and changes this in plain function calls to undefined.
In TypeScript you rarely write it by hand. Code in ES modules (any file with import or export) is always strict, and the compiler option alwaysStrict emits the directive into every output file. Do not confuse it with the strict compiler option, which is a family of type-checking flags.
"use strict"; // the rest of the file runs in strict mode
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
"use strict"; // at the very top of a file function f() { "use strict"; /* ... */ }
| Where | Effect |
|---|---|
| First statement in a file or function | Enables strict mode for that scope. A directive after other statements is just a string. |
| ES module or class body | Strict automatically; no directive needed. |
alwaysStrict (tsconfig) |
Parses every file in strict mode and emits "use strict" in output for non-module files. Included in strict. |
Usage notes
- What changes at runtime: assignments to undeclared names, read-only properties and getter-only properties throw;
deleteon non-configurable properties throws; duplicate parameter names and octal literals like010are errors;thisisundefinedin plain calls;argumentsno longer aliases parameters;withis forbidden. - TypeScript catches most of it first. Writing to an undeclared variable is a type error long before strict mode would throw.
alwaysStrictvsstrict.strict: trueenablesalwaysStrict,noImplicitAny,strictNullChecksand the other strict flags.alwaysStrictis only the runtime-semantics flag.- Module output. When the compiler emits ES modules, no directive is added because it is not needed; for CommonJS output it is added after the module wrapper.
- Function-level directives only work with simple parameter lists: a function with default, rest or destructured parameters cannot contain
"use strict"(error TS1347). - Quotes do not matter, but the directive must be a bare string statement, with no parentheses or concatenation.
Related
delete,this- Lessons: Strict mode, tsconfig