patterntypescriptModeratepending
TypeScript strict mode flags explained
Viewed 0 times
strict modestrictnullchecksnoimplicitanytsconfigtype safety
Problem
Need to understand what TypeScript strict mode enables and which individual flags matter most.
Solution
TypeScript strict mode breakdown:
Recommended additional flags:
// tsconfig.json
{
"compilerOptions": {
"strict": true // Enables ALL of the below:
}
}// 1. strictNullChecks (most impactful!)
// Without: string includes null/undefined implicitly
// With: must handle null explicitly
const name: string = null; // Error!
const name: string | null = null; // OK
function greet(name: string | null) {
// name.toUpperCase(); // Error! name might be null
if (name) {
name.toUpperCase(); // OK after null check
}
}
// 2. noImplicitAny
// Without: untyped params default to 'any'
// With: must annotate parameters
function add(a, b) { return a + b; } // Error! a,b are implicit any
function add(a: number, b: number) { return a + b; } // OK
// 3. strictFunctionTypes
// Enforces contravariant parameter types
type Handler = (event: MouseEvent) => void;
const handler: Handler = (event: Event) => {}; // Error!
// MouseEvent is more specific than Event
// 4. strictBindCallApply
// Type-checks .bind(), .call(), .apply()
function add(a: number, b: number) { return a + b; }
add.call(null, 1, 'two'); // Error! 'two' is not number
// 5. noImplicitThis
// Must annotate 'this' type in functions
function onClick(this: HTMLButtonElement) {
this.textContent = 'Clicked'; // OK, 'this' is typed
}
// 6. alwaysStrict
// Emits 'use strict' in every file
// 7. useUnknownInCatchVariables (TS 4.4+)
try {
something();
} catch (e) {
// e is 'unknown', not 'any'
if (e instanceof Error) {
console.log(e.message); // OK after narrowing
}
}Recommended additional flags:
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true, // arr[0] is T | undefined
"noUnusedLocals": true,
"noUnusedParameters": true,
"exactOptionalPropertyTypes": true,
"noFallthroughCasesInSwitch": true
}
}Why
strict: true catches the most bugs per line of config. strictNullChecks alone prevents the majority of 'cannot read property of undefined' runtime errors.
Context
TypeScript project configuration
Revisions (0)
No revisions yet.