ALL LESSONSWEEK 32WEDNESDAY

CONSTRAIN · TYPESCRIPT

Control-flow narrowing

Inference and narrowing30–60 MINUTESCORE + PRACTICAL
01

GROUND

Problem

What becomes confusing, fragile, or impossible without understanding control-flow narrowing? This lesson answers that through explanation, a worked example, two runnable exercises, and a reference solution. No teacher-supplied worksheet is required.

TypeScript added gradual static analysis to JavaScript without replacing its runtime, preserving ecosystem compatibility through erasure.
02

LEARN

Concept explanation

Control-flow narrowing belongs to “Inference and narrowing”. control-flow narrowing is learned by comparing readable, constrained, and deliberately clever implementations against same evidence.

For control-flow narrowing, trace concrete input, state transition, output, and failure through a compile-time relationship that constrains JavaScript while leaving runtime values and external data untrusted.

Types constrain possible programs during analysis, then disappear. Runtime values remain JavaScript values and external data remains untrusted. Apply that model to supplied normal, boundary, and failure cases; each case below names its input and expected evidence.

Observable

Evidence produced by the control-flow narrowing experiment: output, state, trace, bytes, timing, or diagnostics.

Invariant

Condition that must remain true while inputs or implementation of control-flow narrowing change.

Boundary

Point where control-flow narrowing crosses ownership, representation, time, process, network, or trust.

Example bank

Compare normal, boundary, failure, and cross-layer cases. Predict each observation before revealing the explanation.

Baseline · one variable

SETUPSolve control-flow narrowing three ways using identical fixture: Model loading/success/error union and exhaustively render each state.

OBSERVEAll versions preserve Strict compile passes only with exhaustive handling and runtime validation at boundary.; comparison records code size, predictability, and debugging cost.

WHY IT MATTERSThis isolates the normal contract of control-flow narrowing; preserve its raw evidence as the control for every later comparison.

Boundary · same contract, harder input

SETUPRun all three implementations against: Parse unknown JSON through runtime guard.

OBSERVERecord what remains invariant and the first representation, owner, size, or timing value that changes in tsc · hx LSP · emitted JS · source maps.

WHY IT MATTERSA boundary example is useful only when one named dimension changes and everything else stays comparable.

Failure · evidence before repair

SETUPForce every implementation through: Add new union member and require compiler to expose missing branch.

OBSERVECapture the first divergence from the baseline, including exact input, diagnostic, state, and recovery result. Expected recovery: All versions preserve Strict compile passes only with exhaustive handling and runtime validation at boundary.; comparison records code size, predictability, and debugging cost.

WHY IT MATTERSThe diagnostic is part of the interface. Repair the proven cause, not the most visible symptom.

Cross-layer · follow ownership

SETUPTrace control-flow narrowing one layer below its usual abstraction through a compile-time relationship that constrains JavaScript while leaving runtime values and external data untrusted.

OBSERVERead inferred types, diagnostics, emitted JavaScript, declarations, module traces, and source maps.

WHY IT MATTERSThe lower layer is earned when it explains evidence the current layer cannot. Otherwise keep control-flow narrowing at the simpler boundary.

03

SEE

Worked example

Start from supplied lab.ts. Focus: Solve control-flow narrowing three ways using identical fixture: Model loading/success/error union and exhaustively render each state.

  1. Run: npx tsc --strict --noEmit lab.ts
  2. Save baseline evidence. Read inferred types, diagnostics, emitted JavaScript, declarations, module traces, and source maps.
  3. Boundary case: Run all three implementations against: Parse unknown JSON through runtime guard.
  4. Failure case: Force every implementation through: Add new union member and require compiler to expose missing branch.
RESULT
All versions preserve Strict compile passes only with exhaustive handling and runtime validation at boundary.; comparison records code size, predictability, and debugging cost. Starter-level baseline: Strict type checking exits successfully. Changing result.value to a string-only operation produces a compiler diagnostic.
04

START HERE

Starter material

PREREQUISITESNode.js 22+ and npm. TypeScript is installed locally so compiler version is explicit.

ONE-TIME SETUPmkdir reforging-ts && cd reforging-ts && npm init -y && npm install --save-dev typescript

Create lab.ts, paste this exact content, then run the command below.

type Observation<T> = { topic: string; value: T; valid: boolean };

function observe<T>(topic: string, value: T): Observation<T> {
  return { topic, value, valid: value !== undefined };
}

const result = observe("control-flow narrowing", 1);
console.log(result.value);
RUNnpx tsc --strict --noEmit lab.ts

STOP / CLEANUPCompiler exits by itself; no cleanup command required.

05

DO WITH GUIDANCE

Guided exercise

Solve under constraint: control-flow narrowing

  1. Normal case: Solve control-flow narrowing three ways using identical fixture: Model loading/success/error union and exhaustively render each state.
  2. Write predicted evidence from this named case before running starter.
  3. Keep readable baseline, then remove one convenience without hiding behavior.
  4. Run exact normal case. Save commands, inputs, outputs, and diagnostics in notebook.
  5. Explain changed evidence using lesson mental model in no more than five sentences.
Concrete guided solution
  1. Copy the supplied lab.ts unchanged and run: npx tsc --strict --noEmit lab.ts
  2. Write this prediction before inspecting output: All versions preserve Strict compile passes only with exhaustive handling and runtime validation at boundary.; comparison records code size, predictability, and debugging cost.
  3. Perform only the named normal case: Solve control-flow narrowing three ways using identical fixture: Model loading/success/error union and exhaustively render each state.
  4. Save the raw output, then annotate input → transition → evidence. Use tsc · hx LSP · emitted JS · source maps to confirm the transition rather than inferring it.
  5. Compare prediction with evidence; if they differ, keep both and write the rule that explains the difference. Reference baseline: Strict type checking exits successfully. Changing result.value to a string-only operation produces a compiler diagnostic.
06

DO ALONE

Independent exercise

Compare three versions: control-flow narrowing

  1. Create second case from blank file: Run all three implementations against: Parse unknown JSON through runtime guard.
  2. Then create controlled failure: Force every implementation through: Add new union member and require compiler to expose missing branch.
  3. Use tsc · hx LSP · emitted JS · source maps to prove behavior, then repair controlled failure.
  4. Compare result against supplied acceptance checks and reference approach before marking complete.
Concrete independent solution
  1. Duplicate the starter into a clean comparison case; change only this boundary: Run all three implementations against: Parse unknown JSON through runtime guard.
  2. Save its evidence beside the baseline and identify the first changed value. Read inferred types, diagnostics, emitted JavaScript, declarations, module traces, and source maps.
  3. Create the exact controlled failure: Force every implementation through: Add new union member and require compiler to expose missing branch.
  4. Version A: use clearest native primitives and name every intermediate state for control-flow narrowing.
  5. Version B: remove one convenience while preserving same input/output contract.
  6. Version C: compress only after A and B pass baseline: Model loading/success/error union and exhaustively render each state.
  7. Run shared boundary and failure fixtures against all versions: Parse unknown JSON through runtime guard. / Add new union member and require compiler to expose missing branch.
  8. Keep A unless another version has measured benefit; expected invariant: Strict compile passes only with exhaustive handling and runtime validation at boundary.
  9. Rerun baseline, boundary, and repaired failure together. Accept only if all reproduce: All versions preserve Strict compile passes only with exhaustive handling and runtime validation at boundary.; comparison records code size, predictability, and debugging cost.
07

COMPARE

Expected result

  • All versions preserve Strict compile passes only with exhaustive handling and runtime validation at boundary.; comparison records code size, predictability, and debugging cost.
  • Strict type checking exits successfully. Changing result.value to a string-only operation produces a compiler diagnostic.
  • Controlled control-flow narrowing failure produces captured evidence; repair restores stated invariant without hiding error.
08

PROVE

Acceptance checks

Lesson is complete only when every check is true. Each check is stored locally and travels with your JSON backup.

0/5 complete · saved on this device

09

UNSTICK

Hints

Reveal hints
  1. Start with supplied normal case exactly as written: Solve control-flow narrowing three ways using identical fixture: Model loading/success/error union and exhaustively render each state.
  2. For boundary case, change only named dimension: Run all three implementations against: Parse unknown JSON through runtime guard.
  3. If result is confusing, diff raw inputs and evidence before editing implementation.
  4. If tool shows nothing useful, move observation one boundary lower: representation, runtime, OS, or network.
10

VERIFY

Solution

Attempt both exercises before opening reference approach.

Reveal reference solution
  1. Run unmodified starter and preserve baseline evidence: Strict type checking exits successfully. Changing result.value to a string-only operation produces a compiler diagnostic.
  2. Version A: use clearest native primitives and name every intermediate state for control-flow narrowing.
  3. Version B: remove one convenience while preserving same input/output contract.
  4. Version C: compress only after A and B pass baseline: Model loading/success/error union and exhaustively render each state.
  5. Run shared boundary and failure fixtures against all versions: Parse unknown JSON through runtime guard. / Add new union member and require compiler to expose missing branch.
  6. Keep A unless another version has measured benefit; expected invariant: Strict compile passes only with exhaustive handling and runtime validation at boundary.
11

PREDICT · INSPECT · BREAK · DEBUG · MEASURE

Interrogate reality

Prediction: write expected output, state transition, ordering, and failure evidence before running either exercise.

Inspection: Read inferred types, compiler diagnostics, emitted JavaScript, declaration output, module traces, and source maps.

Measurement: Track compile time, declaration complexity, editor latency, escape hatches, and defects prevented.

INSPECT

Capture raw evidence before explaining.

BREAK

Change one assumption and force controlled failure.

DEBUG

Find cause with tsc · hx LSP · emitted JS · source maps before editing fix.

TOOL DRILL · keyboard only · record one retrievable command or shortcut
12

MASTERY + FRONTIER + BOUNDARY

Own the knowledge

TEACH

Explain control-flow narrowing at beginner, intermediate, and senior depth.

REBUILD

Recreate smallest useful example from blank file without notes or AI.

RETRIEVE

Schedule recall for day 1, 7, 30, and 90.

Creative frontier lab

Try first without opening the solutions. The constraints invite invention; the reference gives one concrete direction, never the only valid answer.

Constraint inversion

Re-solve control-flow narrowing by removing the most convenient abstraction. make invalid states unrepresentable without assertions or broad escape hatches.

CONSTRAINTKeep the same inputs, observable result, and failure evidence; change the means, not the contract.

ORIGINAL IDEATurn subtraction into a design tool: the missing abstraction should reveal which responsibility it used to hide.

Reveal frontier solution
  1. Freeze the contract as three fixtures: Solve control-flow narrowing three ways using identical fixture: Model loading/success/error union and exhaustively render each state. / Run all three implementations against: Parse unknown JSON through runtime guard. / Force every implementation through: Add new union member and require compiler to expose missing branch.
  2. List every convenience used by the starter; remove the highest-level one while preserving npx tsc --strict --noEmit lab.ts.
  3. Implement the smallest replacement using make invalid states unrepresentable without assertions or broad escape hatches.
  4. Run all fixtures and compare raw evidence. Keep the simpler version unless the removed abstraction has a demonstrated benefit.
Representation x-ray

Build an explanation artifact for control-flow narrowing: place inferred type, emitted JavaScript, runtime value, and boundary validation side by side.

CONSTRAINTA peer must be able to locate the first divergence without reading implementation code.

ORIGINAL IDEATreat the explanation itself as a product: make invisible transitions visible, replayable, and diffable.

Reveal frontier solution
  1. Create one row or timestamped event for each transition in: Solve control-flow narrowing three ways using identical fixture: Model loading/success/error union and exhaustively render each state.
  2. For every row record input, representation, owner, operation, output, and tool evidence from tsc · hx LSP · emitted JS · source maps.
  3. Replay Run all three implementations against: Parse unknown JSON through runtime guard.; highlight only changed rows.
  4. Replay Force every implementation through: Add new union member and require compiler to expose missing branch.; stop at the first divergent row and attach its recovery action.
Adversarial remix

Combine the boundary and failure into a new user-visible scenario for control-flow narrowing. generate an exhaustive table whose new row intentionally breaks compilation until handled.

CONSTRAINTDo not merely add more input. Invent a recovery interaction, alternate representation, or self-checking behavior.

ORIGINAL IDEAMake the system teach its own limits: the artifact should expose the invariant and offer a safe next action when it breaks.

Reveal frontier solution
  1. Combine these two pressures without changing them: Run all three implementations against: Parse unknown JSON through runtime guard. AND Force every implementation through: Add new union member and require compiler to expose missing branch.
  2. Name the invariant that must survive and the user-visible evidence when it cannot: All versions preserve Strict compile passes only with exhaustive handling and runtime validation at boundary.; comparison records code size, predictability, and debugging cost.
  3. Implement this original direction: generate an exhaustive table whose new row intentionally breaks compilation until handled.
  4. Demonstrate baseline, combined failure, recovery, then baseline again; save the sequence as a regression fixture.

Capability frontier

Push control-flow narrowing until another layer becomes justified. Record one robust technique, one contextual trade-off, and one labeled hack or historical curiosity.

CORE · PRACTICAL · CONTEXTUAL · HACK · FRAGILE · HISTORICAL · GOLF

Boundary

A type proof cannot validate network data, permissions, temporal behavior, performance, or implementation honesty.

If this vanished tomorrow…

Use runtime validation, tests, contracts, documentation, and disciplined JavaScript data modeling.

Why next layer is earned

Node is earned when trusted server-side work, shared state, filesystem access, or remote coordination becomes necessary.