How TypeScript Works: Mental Models and Tsconfig.json
An introduction to some core TypeScript concepts and mental models for how to think about TypeScript.
Listen to Article
How TypeScript Works: Mental Models and Tsconfig.json
Mental models for TypeScript
Superset of JavaScript
- TypeScript is a superset of JavaScript.
- This essentially means that TypeScript is JavaScript with extra stuff.
- Every valid JavaScript program is also syntactically valid TypeScript.
- TypeScript adds syntax for types (annotations, interfaces, type aliases, generics) on top of JavaScript.
Compile-time vs runtime
- TypeScript performs static analysis before code runs.
- Once code is running in the runtime environment (browser, Node.js, Deno, etc), TypeScript's type system is no longer enforcing anything unless runtime validation (e.g., Zod, Valibot) or runtime checks are explicitly written.
A good mental model
- A good way to think about TypeScript is as a sophisticated linter and transpiler with deep knowledge of data flow and control, rather than a runtime execution engine.
Structural typing ("duck typing") with static guarantees
TypeScript uses structural (shape-based) typing rather than nominal (name-based) typing for most constructs:
- If two types have compatible shapes (properties and method signatures), TypeScript considers them assignable to each other, regardless of whether they have different names.
- Exception: Classes with
privateorprotectedmembers have branding/nominal-like constraints because those members must originate from the same declaration. - Distinct
enumdeclarations also behave nominally in certain contexts.
Example:
Control flow analysis and narrowing
TypeScript doesn't just look at static declarations. It tracks how types change along execution branches:
- Type guards (
typeof,instanceof,'prop' in obj, discriminated unions) narrow a wide union type down to a specific member inside a branch. - Assignments can also can also narrow or widen types depending on context and
strictNullChecks.
The compilation pipeline
Understanding the TypeScript compilation pipeline explains:
- Why errors happen.
- How emit works.
- Where build tools fit in.
- Source text → Scanner (Lexer): Breaks
.ts/.tsx/.mts/.ctstext into a stream of tokens (keywords, identifiers, operators, literals, punctuation). - Tokens → Parser: Builds an Abstract Syntax Tree (AST) representing the syntactic structure of your code (and records syntax errors if grammar is invalid).
- AST → Binder: Creates symbols and links declarations with scopes (e.g., connecting a variable reference to its declaration, merging declarations where allowed, like interfaces or namespaces).
- Bound AST → Type Checker: Walks AST to infer and verify types, check assignability, resolve generics, evaluate conditional/mapped types, and collect semantic diagnostics (type errors).
- Typed AST → Emitter: Transforms the AST into output files - typically
.js(downleveled to your specifiedtargetJS version),.d.ts(declaration files for library consumers) and.d.ts.map/.js.map(source maps).
Type-Checking vs Emitting
- By default,
tscwill still emit.jsfiles even when type errors occur, unless you pass--noEmitOnError. - Modern bundlers and transpilers (like Babel, SWC, esbuild, or Vite's transform step) often strip types without running full type-checking for speed - meaning that
tsc --noEmit(ortsgo/ editor diagnostics) remains essential in CI.
Type erasure and runtime reality
Type erasure is the process by which TypeScript removes type-level constructs when emitting JavaScript.
What gets erased
- Type annotations (
const count: number = 5→const count = 5;). interfaceandtypealiases completely disappear in emitted JavaScript.- Generic type parameters (
function identity<T>(x: T): T→function identity(x) { return x; }). as/ satisfies type assertions (checked/used at compile time, erased at runtime).- Parameter property modifiers (
public,private,protected,readonlyon constructor params are used for type checking/emitting assignments, not kept as runtime type metadata).
What does not get erased (runtime constructs)
- Enums (standard numeric/string
enums emit a runtime object;const enumis inlined/erased depending on flags and isolated modules). - Classes (emitted as JavaScript classes/constructor functions).
- Namespaces (if they contain runtime values).
Common mistakes with type erasure
- Checking an interface with
instanceof: Interfaces don't exist at runtime, sovalue instanceof Userwill not work.instanceofonly works on runtime constructor functions/classes. - Assuming generics exist at runtime: You cannot inspect
Tat runtime to branch logic. If you need runtime behaviour, pass a value/schema/factory function. - Unvalidated external data: Typing an API response as
Promise<User>tells the compiler to trust that shape - it does not parse or validate JSON at runtime.
tsconfig.json and essential strict compiler flags
tsconfig.json defines the root of a TypeScript project, specifies input files, and configures the compiler (compilerOptions).
Enabling strict
Setting "strict": true in tsconfig.json is an umbrella flag that enables a core set of strict type-checking options (and makes future strict checks easier to adopt).
Important flags outside of strict
While not in the strict umbrella, experienced teams commonly pair strict: true with:
noUncheckedIndexedAccess: Adds| undefinedto index signature / array / record lookups (arr[0]becomesT | undefined), catching out-of-bounds reads.exactOptionalPropertyTypes: Distinguishes{ x?: number }(can be omitted orundefinedif explicitly allowed) from{ x?: number | undefined }.noImplicitOverride: Requires theoverridekeyword when overriding a base class method, preventing accidental typos from silently creating new methods.isolatedModules(orerasableSyntaxOnlyin modern TypeScript): Ensures files can be safely transpiled in isolation by single-file bundlers/transpilers and clarifies syntax that relies on type erasure.
Stay Connected
Get notified whenever we publish new articles, insights, guides and product updates.