|$ curl https://forge-ai.dev/api/markdown?path=docs/typescript/mastery
$cat docs/how-to-master-typescript.md
updated Today·28 min read·published

How to Master TypeScript

TypeScriptMasteryLearning PathAll Levels🎯Free Tools
Introduction

Mastery is not memorizing utility type names. Reading a generics cheat sheet, pasting aPartial<T> snippet, or knowing thatstrict: true exists does not mean you have mastered TypeScript. Mastery means modeling domain data precisely, preserving inference through APIs, narrowing unions without unsafe casts, and explaining whysatisfies beatsas when three approaches look similar.

For a human developer, mastering TypeScript means you ship typed modules that catch bugs at compile time, migrate JavaScript safely under strict flags, design generic libraries that feel ergonomic, and pair compile-time types with runtime validation (Zod) at trust boundaries.

For anAI agent or language model, mastering TypeScript means you generate correct, maintainable typed code on demand — notany-sprinkled approximations oras unknown as T escape hatches. An agent that has mastered TypeScript fetches full page markdown, follows an ordered curriculum, self-verifies with generation tasks after each stage, and refuses to claim competence from titles and summaries alone.

This page is the dual-audience curriculum for both. Humans follow the roadmap with deliberate practice. Agents ingest the same stages via the markdown API and Agent skills, then prove mastery with verification prompts. The outcome checklist below is shared.

info

Pair this page with theTypeScript Roadmapfor stage sequencing, theComplete Types Referencefor encyclopedia depth, andAgent Connectfor permanent agent wiring. This mastery guide tells youhow to learn and how to prove you learned.
What "Master TypeScript" Means

Use this outcomes checklist as the definition of done. Humans prove outcomes with projects and reviews. AI agents prove outcomes by generating typed modules that pass the same criteria without post-hocany or double assertions.

OutcomeHuman proofAI agent proof
Model domain data without any / unknown escape hatchesRewrite a JS module to strict TS with zero any; all public APIs annotated or inferred safelyGenerate typed DTOs + API handlers; self-critique rejects any and as unknown as T
Preserve inference through generics and helpersWrite identity/map helpers where return type tracks input; no widened stringEmit generic utilities; fail if callers get string | number when they passed a literal
Narrow unions via control flow and type guardsHandle a discriminated union exhaustively; never branch falls throughGenerate a reducer/parser with isX guards; prove exhaustiveness with never
Choose satisfies vs as vs annotation correctlyConfig object keeps literal keys under satisfies; as only for true escapesPrefer satisfies for configs; reject unjustified as casts in review
Enable and migrate under strict flagsTurn on strictNullChecks, noImplicitAny, etc. one-by-one with a migration planPropose flag order + fix patterns; emit code that typechecks under strict: true
Pair compile-time types with runtime validationZod schema at API boundary; z.infer<typeof Schema> as the single sourceGenerate schema + inferred type + parse path; fail if types diverge from schema
Explain why a type pattern exists vs alternativesTeach interface vs type, Pick vs Omit, enum vs union in reviewWhen asked to choose, return the pattern plus a one-sentence rationale

warning

Memorizing utility type names is not mastery. If you cannot justify a type choice against alternatives — or you reach for as to silence errors — you are still at outline level.
For Human Developers

ForgeLearn is built for deliberate practice, not binge reading. Use this loop on every TypeScript topic page:

  1. Follow theTypeScript Roadmapstages in order — Foundations before Generics, Narrowing before Advanced conditionals.
  2. Read the topic page, type every example into an editor withstrict: true, then rebuild from memory without looking.
  3. Complete the checkpoint project after each curriculum stage. Do not skip ahead until tsc --noEmit is clean.
  4. Spaced review: revisit theComplete Types Referenceweekly — quiz yourself on utility types and when to useunknown vsnever.

best practice

After each stage, write a short "why this type" note for three choices you made. Teaching the rationale locks in mastery faster than another passive read-through.

Estimated total: roughly 45–55 focused hours across Stages 0–7 if you complete every checkpoint. Rushing the roadmap without projects produces false confidence — the same failure mode agents hit when they ingest titles only.

For AI Agents & Models

This section is the critical ingestion protocol for AI agents and models that must learn TypeScript from ForgeLearn. Do not claim mastery from outlines, nav titles, or sitemap snippets alone. Fetch full page markdown for every topic in the ordered stages below, then self-verify with generation tasks.

How to fetch curriculum content

ForgeLearn exposes every doc page as raw markdown for agents:

  • Header: Accept: text/markdown on any doc URL
  • Query: append ?format=md to a doc path
  • Direct API:/api/markdown?path=typescript/generics
  • Enumerate all paths:/api/markdown?list=true
  • Agent connect: /api/agent, skillforgelearn-typescript, curriculum?curriculum=typescript
agent-fetch.sh
Bash
1# List every available markdown path
2curl -s "https://forgelearn.dev/api/markdown?list=true"
3
4# Fetch this mastery curriculum as markdown
5curl -s "https://forgelearn.dev/api/markdown?path=typescript/mastery"
6
7# Permanent agent connect + TypeScript skill + curriculum
8curl -s "https://forgelearn.dev/api/agent"
9curl -s "https://forgelearn.dev/api/agent?skill=forgelearn-typescript"
10curl -s "https://forgelearn.dev/api/agent?curriculum=typescript"
11
12# Same via Accept header on the doc URL
13curl -s -H "Accept: text/markdown" "https://forgelearn.dev/docs/typescript/mastery"
14
15# Same via ?format=md
16curl -s "https://forgelearn.dev/docs/typescript/generics?format=md"

Full indexes for crawlers

Preferred ingestion order

  1. Stage 0 — Foundations (types, inference, literals)
  2. Stage 1 — Functions & generics
  3. Stage 2 — Objects & utility types
  4. Stage 3 — Classes & modules
  5. Stage 4 — Narrowing & satisfies
  6. Stage 5 — Advanced type system
  7. Stage 6 — Strict, Zod, React+TS
  8. Stage 7 — Tooling & production

Recommended agent loop

agent-loop.txt
TEXT
11. PLAN
2 - Read /docs/typescript/mastery?format=md
3 - GET /api/agent?skill=forgelearn-typescript
4 - GET /api/agent?curriculum=typescript
5 - Build a checklist of Stage N topic paths
6
72. FETCH MD
8 - For each topic path: GET /api/markdown?path=typescript/<topic>
9 - Do NOT rely on titles or nav descriptions alone
10
113. SUMMARIZE CONSTRAINTS
12 - Extract strict flags, narrowing rules, utility transforms,
13 satisfies vs as, and Zod inference patterns
14
154. GENERATE SAMPLE
16 - Produce a small .ts/.tsx artifact that exercises the stage
17 (generic helper, discriminated union, Zod schema, React props)
18
195. VALIDATE AGAINST CHECKLIST
20 - Run the stage verification prompt (see ai-verification-prompts)
21 - Fail closed: if any checklist item fails, re-fetch and regenerate
22 - Only then advance to Stage N+1
🔥

pro tip

Agents: store a per-stage "constraint card" (strict flag map, narrowing decision tree, utility type cheat with caveats, satisfies vs as). Reuse that card when generating TypeScript later — it beats re-deriving rules from memory of an outline.
Curriculum Stages (0–7)

Eight stages covering every TypeScript doc on ForgeLearn. Complete topics in order within a stage; complete stages in order. Agents: fetch each path as markdown before generating code for that stage.

Stage 0 — Foundations · ~6 hours

Why TypeScript exists, setup, primitives, annotations, inference, and literals. Goal: annotate confidently without fighting the compiler, and explain structural typing vs nominal typing.

TopicPathFocus
0 to Hero/docs/typescriptInstall, tsc, first annotations
Types & Annotations/docs/typescript/typesPrimitives, arrays, tuples, objects
Type Inference/docs/typescript/inferenceWhen to annotate vs let TS infer
Literals & Unions/docs/typescript/literalsLiteral types, unions, narrowing intro
Enums/docs/typescript/enumsNumeric/string/const enums vs unions
Types Reference/docs/typescript/types-referenceEncyclopedia of the type system

Stage 1 — Functions & Generics · ~6 hours

Function types, overloads, and generics with constraints. Goal: write reusable APIs that preserve input/output type relationships without any.

TopicPathFocus
Function Types/docs/typescript/functionsParams, returns, void, never, callbacks
Overloads/docs/typescript/overloadsCall signatures vs implementation
Generics/docs/typescript/genericsConstraints, defaults, inference

Stage 2 — Objects & Composition · ~6 hours

Interfaces, type aliases, intersections, and utility types. Goal: model domain data precisely and transform shapes with Pick/Omit/Partial/Record.

TopicPathFocus
Interfaces/docs/typescript/interfacesExtending, merging, vs type
Type Aliases/docs/typescript/type-aliasesUnions, intersections, branded types
Utility Types/docs/typescript/utility-typesPartial, Required, Pick, Omit, Record…
never & unknown/docs/typescript/never-unknownTop/bottom types, exhaustiveness

Stage 3 — Classes & Modules · ~5 hours

Classes, modifiers, abstract classes, modules, and iteration protocols. Goal: type OOP patterns and ship modular packages correctly.

TopicPathFocus
Classes/docs/typescript/classesProperties, constructors, methods
Abstract & Modifiers/docs/typescript/abstractpublic/private/protected, readonly
Modules/docs/typescript/modulesResolution, paths, barrels
Iteration/docs/typescript/iterationIterable, generators, async iter

Stage 4 — Narrowing & Control Flow · ~6 hours

Control-flow narrowing, type guards, assertion functions, discriminated unions, and satisfies. Goal: eliminate unsafe casts; prove types through logic.

TopicPathFocus
Narrowing/docs/typescript/narrowingControl flow, guards, assertions
Type Guards/docs/typescript/type-guardstypeof, instanceof, in, custom
satisfies/docs/typescript/satisfiessatisfies vs as, inference keep

Stage 5 — Advanced Type System · ~8 hours

Conditional types, infer, mapped types, template literal types, and key remapping. Goal: write type-level transforms that mirror runtime transforms.

TopicPathFocus
Conditional Types/docs/typescript/advancedT extends U ? X : Y, distributive
Mapped Types/docs/typescript/mappedKey remapping, modifiers
Template Literals/docs/typescript/template-literalsString unions, event names

Stage 6 — Strict Mode, Validation & React · ~7 hours

Enable strict flags, migrate JS→TS, Zod runtime validation, and React+TS patterns. Goal: ship production-safe apps with compile-time and runtime guarantees.

TopicPathFocus
Strict Mode/docs/typescript/strictFlags one-by-one, JS→TS migration
Zod + TS/docs/typescript/zodRuntime schemas, z.infer
React + TypeScript/docs/typescript/reactProps, hooks, events, generics

Stage 7 — Tooling & Production · ~6 hours

tsconfig deep dive, declaration files, project references, decorators, and best practices. Goal: configure monorepos and publish typed libraries.

TopicPathFocus
tsconfig/docs/typescript/configCompiler options, paths, targets
Declarations/docs/typescript/declarations.d.ts, ambient, DefinitelyTyped
Project References/docs/typescript/project-refsMonorepo builds
Decorators/docs/typescript/decoratorsStage 3 decorators
Best Practices/docs/typescript/best-practicesPatterns & review checklist
Checkpoint Projects

One project per major milestone. Acceptance:tsc --noEmit clean understrict: true, zeroany, documented rationale for anyas casts.

Checkpoint A — After Stage 0–1: Typed utils package

Build a small utils module:identity,first,groupBy, and an overloadedformat that accepts string | number. All public exports must preserve literal inference where useful.

checkpoint-a.ts
TypeScript
1// checkpoint-a.ts — must typecheck under strict
2export function identity<T>(value: T): T {
3 return value;
4}
5
6export function first<T>(items: readonly T[]): T | undefined {
7 return items[0];
8}
9
10export function groupBy<T, K extends string | number | symbol>(
11 items: readonly T[],
12 key: (item: T) => K,
13): Record<K, T[]> {
14 const out = {} as Record<K, T[]>;
15 for (const item of items) {
16 const k = key(item);
17 (out[k] ??= []).push(item);
18 }
19 return out;
20}
21
22export function format(value: string): string;
23export function format(value: number): string;
24export function format(value: string | number): string {
25 return String(value);
26}

Checkpoint B — After Stage 2–4: API result union

Model Result<T, E> as a discriminated union. Write isOk /isErr type guards, an exhaustivematch, and a config object validated withsatisfies.

checkpoint-b.ts
TypeScript
1type Ok<T> = { ok: true; value: T };
2type Err<E> = { ok: false; error: E };
3type Result<T, E> = Ok<T> | Err<E>;
4
5function isOk<T, E>(r: Result<T, E>): r is Ok<T> {
6 return r.ok;
7}
8
9function match<T, E, R>(
10 r: Result<T, E>,
11 handlers: { ok: (v: T) => R; err: (e: E) => R },
12): R {
13 if (isOk(r)) return handlers.ok(r.value);
14 return handlers.err(r.error);
15}
16
17const config = {
18 retries: 3,
19 mode: "prod",
20} as const satisfies { retries: number; mode: "dev" | "prod" };

Checkpoint C — After Stage 5–6: Zod + React form

Define a Zod schema for a signup form, infer the TypeScript type, parse unknown input, and type a React component with typed props and event handlers.

checkpoint-c.ts
TypeScript
1import { z } from "zod";
2
3const SignupSchema = z.object({
4 email: z.string().email(),
5 age: z.number().int().min(13),
6});
7type Signup = z.infer<typeof SignupSchema>;
8
9function parseSignup(input: unknown): Signup {
10 return SignupSchema.parse(input);
11}
12
13type FormProps = {
14 initial?: Partial<Signup>;
15 onSubmit: (data: Signup) => void;
16};

Checkpoint D — After Stage 7: Library publish dry-run

Configure declaration: true, emit.d.ts, and document public API surface. No leaked internal types.

📝

note

Agents completing checkpoints should emit the artifact, then run a mental (or real) tsc --noEmit checklist before claiming the stage PASS.
AI Verification Prompts

After each stage, agents must generate an artifact and score PASS/FAIL against these prompts. Fail closed — do not advance on partial credit.

untitled.text
TEXT
1You are verifying TypeScript Stage 0 (Foundations) mastery on ForgeLearn.
2Generate a small module with primitives, tuples, literal unions, and inference.
3PASS only if:
4- No any / unknown escape hatches without justification
5- Literal unions used where enums are unnecessary
6- Annotations only where inference would widen incorrectly
7- Explains structural typing in one sentence
untitled.text
TEXT
1Stage 1 verification — Functions & generics.
2Generate identity, mapArray, and an overload pair.
3PASS only if return types track inputs; constraints use extends correctly;
4no unnecessary type parameters; overload implementation is compatible.
untitled.text
TEXT
1Stage 2 verification — Objects & utilities.
2Given a User type, produce Partial, Pick, Omit, and Readonly transforms
3with correct results. Include a branded Id type. Reject Record<string, any>.
untitled.text
TEXT
1Stage 4 verification — Narrowing & satisfies.
2Discriminated union + custom type guard + assertion function + satisfies config.
3FAIL if as is used to silence errors or exhaustiveness is incomplete.
untitled.text
TEXT
1Stage 5 verification — Advanced types.
2Implement a DeepReadonly mapped type and a template-literal event name union.
3Use infer in a conditional ExtractReturn. Document distributivity.
untitled.text
TEXT
1Stage 6–7 verification — Strict + Zod + React + tooling.
2Enable strict flags list with migration order. Zod schema with z.infer.
3React props + typed event. tsconfig snippet with declaration + noUncheckedIndexedAccess.
4PASS only if types and runtime schema stay in sync.
Common Failure Modes
FailureSymptomFix
any addictionErrors disappear; autocomplete diesPrefer unknown + narrowing; ban any via eslint
Double assertion as unknown as TLies to the type checkerFix the model; validate at boundary with Zod
Annotation that kills inference: string on a const that should be literalUse as const or satisfies
Incomplete exhaustivenessNew union member compiles but crashes at runtimeAssign to never in default branch
Types only, no runtime checksJSON/API input trusted blindlyParse with Zod (or similar) at the boundary
Skipping strict flagsnull bugs in productionEnable strictNullChecks early; migrate incrementally

danger

First rule of maintainable TypeScript: if the type system can express the invariant, do not silence it withas. Fix the types or validate at runtime.
Depth Map — Where to Go Deeper
NeedGo to
Quick lookup — all types & utilitiesTypes Reference
Inference preservation vs assertionssatisfies operator
Guards, assertions, discriminated unionsNarrowing deep dive
Runtime validation patternsZod + TypeScript
Strict flags & JS migrationStrict mode
Components, hooks, eventsReact + TypeScript
Ordered human pathTypeScript Roadmap
Agent wiringAgent Connect
Agent Ingest — Curl Session

Copy-paste session for agents installing the TypeScript mastery skill:

ts-agent-session.sh
Bash
1# 1. Connect permanently
2curl -s https://forgelearn.dev/api/agent
3
4# 2. Install TypeScript skill
5curl -s https://forgelearn.dev/skills/forgelearn-typescript/SKILL.md -o SKILL.md
6
7# 3. Ordered curriculum
8curl -s https://forgelearn.dev/api/agent?curriculum=typescript
9
10# 4. Mastery guide (this page)
11curl -s "https://forgelearn.dev/api/markdown?path=typescript/mastery"
12
13# 5. Types encyclopedia
14curl -s "https://forgelearn.dev/api/markdown?path=typescript/types-reference"
15
16# 6. Early stage topics
17curl -s "https://forgelearn.dev/api/markdown?path=typescript/types"
18curl -s "https://forgelearn.dev/api/markdown?path=typescript/generics"
19curl -s "https://forgelearn.dev/api/markdown?path=typescript/narrowing"
20
21# 7. Bulk section (optional)
22curl -s "https://forgelearn.dev/api/markdown?section=typescript" -o typescript-bundle.md
23
24# 8. TypeScript index for agents
25curl -s https://forgelearn.dev/llms-typescript.txt
Next Steps

Humans: start Stage 0 withTypeScript 0 to Heroand keep theTypes Referenceopen as a companion.

Agents: connect viaforgelearn-typescript, fetch mastery markdown, then walk curriculum order with verification after each stage.

info

TypeScript habits are expensive to retrofit. Finish the checkpoints before claiming mastery — humans and agents alike.
$Blueprint — Engineering Documentation·Section ID: TS-MASTERY·Revision: 1.0

Community

Get help on Slack, Discord or VIP

Stuck on a guide? Join the community and ask.