Full Strict Settings in tsconfig.json
strict: true is a shorthand that enables a group of strict checking settings simultaneously. Understanding what each one does helps you reason about the errors it surfaces and make informed decisions about which additional settings to layer on top. The two settings not included in strict: true that we add to every project are exactOptionalPropertyTypes and noUncheckedIndexedAccess — they catch a significant class of bugs that the base strict flag misses.
- strictNullChecks: prevents using null/undefined without checking first
- strictFunctionTypes: precise checking of function parameter types
- noImplicitAny: no implicit any — forces you to be explicit
- noImplicitReturns: every function path must return a value
- Add: exactOptionalPropertyTypes, noUncheckedIndexedAccess for maximum strictness
- noFallthroughCasesInSwitch: each switch case must end with break, return, or throw
- useUnknownInCatchVariables: catch clause variable is unknown, not any — forces type checking
- forceConsistentCasingInFileNames: prevents OS-dependent import bugs on case-insensitive filesystems
Correctly Handling Null and Undefined
Null and undefined handling is where strict mode pays the biggest dividends. TypeScript's strictNullChecks forces you to acknowledge the possibility of null or undefined at every point where it could occur, which is exactly where production null-reference errors happen. The patterns below are not just defensive programming — they are idiomatic TypeScript that makes null handling explicit and the code self-documenting.
- Optional chaining: user?.profile?.avatar ?? defaultAvatar
- Non-null assertion (!): use only when you are 100% certain
- Type guards: if (user !== null) instead of type assertions
- Nullish coalescing (??): better than || because it doesn't exclude 0 and empty strings
- Result pattern: { data, error } instead of exceptions for expected errors
- Narrowing: TypeScript narrows the type inside an if block — use this instead of casting
- Array bounds: noUncheckedIndexedAccess makes arr[0] be T | undefined — forces the check
- Optional properties vs undefined union: { x?: string } vs { x: string | undefined } — subtle but important with exactOptionalPropertyTypes
Discriminated Unions: TypeScript's Most Powerful Pattern
Discriminated unions replace a class of runtime errors with compile-time exhaustiveness checking. Instead of checking status strings or boolean flags and hoping all cases are handled, TypeScript's exhaustiveness checking via never guarantees that adding a new state to the union forces the compiler to identify every switch statement that does not handle it. This makes adding new features safer and refactoring more reliable.
- type Result<T> = { ok: true; data: T } | { ok: false; error: string }
- switch(result.ok): TypeScript knows exactly the type in each branch
- State pattern: type State = Loading | Success | Error — each state its own type
- Exhaustive checks: default: assertNever(state) ensures all cases are covered
- Very useful for API responses, form states, async operations
- Event union: type UserEvent = LoginEvent | LogoutEvent | UpdateProfileEvent
- The discriminant: typically a literal type string field named 'type' or 'kind'
- Pattern matching: combine with switch + narrowing for zero-cost type safety at every branch
Branded Types: Preventing Mixing of Similar Values
In a typical LMS platform, userId, courseId, enrollmentId, and lessonId are all strings or numbers — structurally identical types that the compiler cannot distinguish. Branded Types add a phantom type marker that makes each domain ID unique to the type system, preventing the entire class of bugs where the wrong ID type is passed to the wrong function. The cost is zero at runtime — the brand exists only for the compiler.
- type UserId = string & { __brand: 'UserId' }
- type CourseId = string & { __brand: 'CourseId' }
- function createUser(id: UserId) — won't accept a CourseId even though both are strings
- Constructor function: function toUserId(id: string): UserId { return id as UserId; }
- Zero runtime cost — disappears after compilation, benefit is compile-time only
- Validate at boundary: brand IDs when they enter the system (API request parsing)
- Zod integration: z.string().brand('UserId') creates a branded Zod schema with correct output type
- Consistent naming: suffix all branded types with their domain concept — UserId, CourseId, not just Id
Most-Used Utility Types in Production Code
TypeScript's built-in utility types enable precise type transformations without type duplication. Instead of defining a separate UpdateUserPayload type by hand, Partial<User> expresses it correctly with zero maintenance overhead. Learning which utility type fits each common pattern saves significant time and keeps types DRY.
- Partial<T>: for update operations where every field is optional
- Required<T>: the reverse — every field mandatory
- Pick<T, Keys>: extract a subset of a type
- Omit<T, Keys>: type without certain fields — Omit<User, 'password'> for API response
- ReturnType<typeof fn>: extract function return type — useful with query functions
- Parameters<typeof fn>: extract function parameter types — for higher-order functions
- Readonly<T>: prevent mutation — useful for config objects and reducer state
- Record<Keys, Values>: typed key-value map — Record<UserId, UserProfile> for lookups
Migrating Existing Code to Strict Mode
Enabling strict mode on an existing codebase with hundreds of files and thousands of errors is not a weekend project — it is an incremental process that works best when done one flag at a time over several sprints. The right approach is to enable the highest-value flag first (strictNullChecks), fix its errors in the most critical files, and suppress the rest temporarily until they can be addressed.
- Don't enable strict: true all at once on a large codebase — thousands of errors
- Start with strictNullChecks: true alone — highest value, least noise
- // @ts-strict-ignore for files not yet migrated
- Add one setting per sprint — gradual accumulation
- VSCode ESLint + typescript-eslint helps with detection and automatic fixes
- ts-migrate: automated tool that adds type annotations to reduce initial error count
- Prioritize migration order: shared lib files first, then the most frequently changing code
- Track progress: keep a count of remaining suppressions as a migration health metric
TypeScript ESLint: Type-Aware Linting
typescript-eslint provides lint rules that use TypeScript's type information, catching issues that neither the compiler nor traditional ESLint can find. Type-aware rules like @typescript-eslint/no-floating-promises catch unawaited promises that silently swallow errors. These rules are slower than regular lint rules because they require type checking — run them separately in CI, not in the pre-commit hook.
- @typescript-eslint/no-floating-promises: catch unawaited async calls that silently fail
- @typescript-eslint/no-misused-promises: prevent async functions in sync callbacks
- @typescript-eslint/strict-boolean-expressions: no truthy coercion on non-boolean values
- prefer-nullish-coalescing: flag || where ?? is more correct
- no-unnecessary-type-assertion: remove useless 'as Type' casts the compiler already knows
- consistent-type-imports: enforce 'import type' for type-only imports — smaller bundles
- Type-aware rules in parserOptions: project must point to tsconfig.json
- Separate lint config: faster pre-commit (no type checking) vs thorough CI (full type-aware)
