Skip to the content.

You Don’t Know TypeScript: How the TypeScript Type System Really Works

A free, open-source deep dive into the TypeScript type system: structural typing, type inference, narrowing, generics, conditional types, mapped types, template literal types, variance and soundness. Ten chapters explain the mental models behind the compiler’s behavior, and every claim is backed by a runnable, type-checked example, so you stop fighting TypeScript errors and start using the type system on purpose. It is for JavaScript and TypeScript developers who can write everyday TypeScript but want to really understand it.

Last reviewed: December 2026. All examples type-check with TypeScript 5.9, 6.0 and 7.0 and run on Node.js 22.18 or later (which runs .ts files directly by stripping types). Feature version numbers are noted where they matter.


Contents


Why This Exists

Most TypeScript tutorials teach syntax: how to write an interface, how to add a generic. Then real code produces errors like *“Type ‘string’ is not assignable to type ‘“dark” “light”’”* or “Type instantiation is excessively deep and possibly infinite”, and the syntax knowledge does not help.

This project teaches the rules underneath:

Each chapter is short, ends with self-check questions, and points to an example file you can run and modify.


Quick Start

Requirements: Node.js 22.18 or later.

git clone https://github.com/Ralpberry-Labs/you-dont-know-typescript.git
cd you-dont-know-typescript
npm install          # installs typescript and @types/node (dev only)

npm run typecheck    # checks every type-level assertion in the examples
npm run test:runtime # runs the runtime tests with node:test
npm run examples     # prints the output of every chapter's demo
npm test             # all of the above

node scripts/run-examples.ts 7   # run one chapter's demo

The best way to read: open a chapter in one window and its example file in your editor in another. Hover over types, change a line, and watch npm run typecheck react.


Chapters

# Chapter You will understand Example
1 Types Are Sets, and Compatibility Is Structural Assignability as subset, structural typing, excess property checks, unknown vs never vs any, optional vs undefined ch01
2 How TypeScript Infers Types Widening, as const, best common type, contextual typing, return inference, satisfies ch02
3 Narrowing and Control Flow Analysis typeof, in, instanceof, discriminated unions, exhaustiveness with never, type predicates, assertion functions ch03
4 Generics: Linking Types Together Constraints, keyof, inference candidates, const type parameters, NoInfer, defaults, generic anti-patterns ch04
5 Conditional Types, Distribution and infer Distributive conditional types, the never trap, pattern matching with infer, deferred types in generic code ch05
6 keyof, Indexed Access and Mapped Types Rebuilding Partial, Pick and Record, modifiers, key remapping, homomorphic mapped types ch06
7 Template Literal Types Building and parsing string types, typed route parameters, limits of pattern types ch07
8 Variance Covariance, contravariance, invariance, method bivariance, array covariance, in and out annotations ch08
9 Type-Level Programming Tuple recursion, typed dot paths, union to intersection, overloads, testing types, when to stop ch09
10 Soundness, Escape Hatches and Staying Safe Type erasure, any vs unknown, assertions, branded types, declaration merging, a safety checklist ch10

Suggested reading order: 1 to 4 in order (they build the core model), then any of 5 to 7, then 8 to 10.


How the Examples Prove Themselves

Every example file mixes three kinds of checks:

  1. Type equality assertions that fail to compile if a claim about a type is wrong:

    type Equal<A, B> =
      (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;
    type Expect<T extends true> = T;
    
    type _test = Expect<Equal<Exclude<"a" | "b", "a">, "b">>;
    
  2. Expected errors using // @ts-expect-error. If the line below stops being an error (for example after a TypeScript upgrade), the directive itself becomes an error, so the example cannot silently go out of date. These lines live inside functions that are never called, so they do not run.

  3. Runtime behavior in each file’s demo() function and in test/runtime.test.ts, run with Node’s built-in test runner.

The project’s tsconfig.json uses strict settings (strict, noUncheckedIndexedAccess, exactOptionalPropertyTypes) and erasableSyntaxOnly, which guarantees every file can run directly in Node without a build step (no enums, namespaces or constructor parameter properties).


The Mental Models on One Page

Concept Mental model Chapter
Type A set of values 1
A assignable to B A is a subset of B 1
More properties Smaller set (a subtype) 1
unknown / never Everything / nothing 1
any Not a set; checking switched off in both directions 1, 10
let vs const Mutable values widen; constants keep literals 2
satisfies Check against a type, keep the inferred type 2
Narrowing Each code location has its own, smaller type for a variable 3
Discriminated union A tag property that selects the variant 3
Generic parameter A type variable that links inputs and outputs 4
Conditional type An if on subset-ness, distributing over naked unions 5
infer Pattern matching that captures part of a type 5
Mapped type A loop over keys 6
Template literal type String templates and parsing at the type level 7
Variance Outputs preserve subtyping, inputs reverse it 8
Types at runtime Erased; validate external data 10

Built-In Utility Types Cheat Sheet

Utility What it does Example result
Partial<T> All properties optional { a?: string }
Required<T> All properties required { a: string }
Readonly<T> All properties readonly (shallow) { readonly a: string }
Pick<T, K> Keep only keys K Pick<User, "id">
Omit<T, K> Remove keys K (K is not checked against keyof T) Omit<User, "password">
Record<K, V> Object with keys K and values V Record<"a" \| "b", number>
Exclude<U, X> Remove union members assignable to X Exclude<"a" \| "b", "a"> is "b"
Extract<U, X> Keep union members assignable to X Extract<string \| 1, number> is 1
NonNullable<T> Remove null and undefined NonNullable<string \| null> is string
ReturnType<F> A function’s return type ReturnType<() => 1> is 1
Parameters<F> A function’s parameter tuple Parameters<(a: string) => void> is [a: string]
Awaited<T> Recursively unwrap promises Awaited<Promise<Promise<number>>> is number
InstanceType<C> Instance type of a constructor InstanceType<typeof Date> is Date
NoInfer<T> Block inference from this position (5.4+) see Chapter 4
Uppercase, Lowercase, Capitalize, Uncapitalize String literal transforms Capitalize<"id"> is "Id"

Chapters 5 and 6 re-implement several of these, which is the fastest way to understand them.


Compiler Options That Change the Rules

Option Effect Recommendation
strict Turns on the strict family: strictNullChecks, strictFunctionTypes, noImplicitAny, useUnknownInCatchVariables and others Always on for new code
strictNullChecks null and undefined are separate types instead of members of every type Essential; included in strict
strictFunctionTypes Function type parameters are checked contravariantly (methods excepted) Included in strict
noUncheckedIndexedAccess arr[i] and record[key] include undefined Recommended; catches real crashes
exactOptionalPropertyTypes prop?: T no longer accepts an explicit undefined Recommended for libraries and APIs
noImplicitOverride Overriding methods must say override Helpful in class hierarchies
verbatimModuleSyntax Type-only imports must use import type Recommended for modern tooling
erasableSyntaxOnly Forbids syntax with runtime meaning (enums, namespaces, parameter properties) Use when running TS directly in Node

Changing these flags changes which code compiles. When you read type errors from someone else’s project, check their tsconfig.json first.


Decoding Common Type Errors

Code Message (shortened) Usually means Chapter
TS2322 Type ‘X’ is not assignable to type ‘Y’ X is not a subset of Y; often widening (string vs a literal union) 1, 2
TS2345 Argument of type ‘X’ is not assignable to parameter of type ‘Y’ Same, at a call site; check generic inference candidates 2, 4
TS2353 Object literal may only specify known properties Excess property check on a fresh literal; usually a typo 1
TS2741 Property ‘p’ is missing in type ‘X’ but required in type ‘Y’ Missing required property, or optional modifiers lost in a mapped type 1, 6
TS2339 Property ‘p’ does not exist on type ‘X’ Not narrowed yet, or p really is not there 3
TS18048 / TS2532 ‘x’ is possibly ‘undefined’ / Object is possibly ‘undefined’ Narrow first, or use noUncheckedIndexedAccess-aware code 3, 10
TS7006 Parameter ‘x’ implicitly has an ‘any’ type No contextual type; annotate the parameter 2
TS2367 This comparison appears to be unintentional because the types have no overlap You compared values that can never be equal; often a narrowed type you forgot 3
TS2589 Type instantiation is excessively deep and possibly infinite Recursive type hit the compiler’s depth limit 9
TS2578 Unused ‘@ts-expect-error’ directive The line no longer errors; update the test or the code 9

Tip: read long assignability errors from the bottom up. The last lines name the specific property and types that actually conflict.


Feature Timeline

Type system features used in this project and the TypeScript version that introduced them:

Version Feature
2.8 Conditional types and infer
3.4 as const assertions
4.0 Variadic tuple types
4.1 Template literal types, key remapping in mapped types
4.4 Control flow analysis of aliased conditions
4.7 Variance annotations (in, out), infer ... extends
4.9 satisfies
5.0 const type parameters
5.4 NoInfer
5.5 Inferred type predicates
5.8 erasableSyntaxOnly

The TypeScript team publishes detailed release notes for every version in the TypeScript documentation.


Exercises

Try these after the matching chapter. Solutions are left to you; check them with Expect<Equal<...>>.

  1. (Ch. 1) Write IsExactly<A, B> using only extends checks in both directions. Find an input where it disagrees with the Equal helper.
  2. (Ch. 2) Make const methods = ["GET", "POST"] produce the type "GET" | "POST" without writing the union by hand.
  3. (Ch. 3) Add a "hexagon" variant to Shape and fix every compile error it causes.
  4. (Ch. 4) Write groupBy<T, K extends PropertyKey>(items: T[], key: (item: T) => K): Record<K, T[]>.
  5. (Ch. 5) Write ParametersOfMethods<T> that maps each method name of T to its parameter tuple.
  6. (Ch. 6) Write Nullable<T> that adds | null to every property, preserving optional modifiers.
  7. (Ch. 7) Write CamelCase<S> that turns "user_id_value" into "userIdValue".
  8. (Ch. 8) Find a method in the standard library type declarations that relies on method bivariance.
  9. (Ch. 9) Extend Paths<T> to include array indices as `${K}.${number}`.
  10. (Ch. 10) Implement a branded Email type with a validating constructor and write tests for it.

FAQ

Is TypeScript’s type system sound? No, intentionally. Chapter 10 lists the main gaps (erasure, any, assertions, method bivariance, array covariance, unchecked indexing) and how to guard against each.

Is TypeScript structurally or nominally typed? Structurally: compatibility depends on shape, not on declared names. Branded types (Chapter 10) add nominal-style checks where you need them.

What is the difference between type and interface? Both describe object shapes. Interfaces can be merged by redeclaring them and can extends other interfaces; type aliases can name any type, including unions, tuples, conditional and mapped types. Many teams use interfaces for public object shapes and type aliases for everything else.

When should I use unknown instead of any? Almost always. unknown accepts every value like any, but forces you to narrow before using it.

What does satisfies do? It checks that an expression matches a type without changing the expression’s inferred type. See Chapter 2.

Why is my conditional type returning a union of arrays? Distribution over a naked type parameter. Wrap it as [T] extends [U] to disable it. See Chapter 5.

Can Node.js run TypeScript files directly? Yes, recent Node versions strip type annotations and run .ts files without a build step, as long as the code only uses erasable syntax. Node does not type-check; run tsc for that.

Do I need these advanced features in application code? Usually not much. Chapters 1 to 4 and 10 pay off in every codebase. Chapters 5 to 9 matter most when you write libraries, shared utilities, or APIs used in many places.


Where to Go Next


Project Layout

chapters/   ten chapters in Markdown
examples/   one runnable, type-checked TypeScript file per chapter
src/        tiny helpers: Equal, Expect, assertNever
test/       runtime tests (node:test)
scripts/    run-examples.ts prints every chapter's demo output

Contributing

Pull requests are welcome. Please keep entries accurate:

License

MIT. Copyright (c) 2026 Ralpberry Labs.

If this helped you, a star helps others find it.

More free resources

Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.