Course contentsShow
← TypeScript
Lesson 1346 of 1,79631. Type-Driven DesignFree lesson

Refactoring Toward Impossible States

Step-by-step process for identifying invalid states in existing code and refactoring to eliminate them.

Refactoring Toward Impossible States

What you'll learn: A systematic process for finding where invalid states exist in your code and transforming types to eliminate them at compile time.

The Refactoring Process

Refactoring toward impossible states isn't a one-shot transformation—it's a deliberate, step-by-step process you can apply to existing code.

Step 1: Identify the Problem States

Start by auditing your current types. Look for:

  • Boolean combinations that create contradictions (isLoading: boolean + data: User | null + error: Error | null)
  • Optional properties that shouldn't coexist (both draftId and publishedId present)
  • Parallel arrays where indices must align (names: string[] and ages: number[])
  • Unrelated optionality where one field requires another

Ask: "What states can I represent that don't make sense?"

Step 2: List Valid State Combinations

Write down only the legitimate states your system should allow:

  • Loading (no data, no error)
  • Success (data present, no error)
  • Failure (error present, no data)

This exercise reveals that { isLoading: false, data: null, error: null } is nonsense.

Step 3: Model as Discriminated Union

Create a union type where each valid state is its own distinct shape:

type LoadingState = { status: 'loading' };
type SuccessState = { status: 'success'; data: User };
type ErrorState = { status: 'error'; error: Error };

type State = LoadingState | SuccessState | ErrorState;

Step 4: Update Construction Points

Find everywhere the old type is created. Replace with explicit state construction:

// Before: setState({ isLoading: true, data: null })
// After:
setState({ status: 'loading' });

Step 5: Narrow at Consumption Points

Replace conditional checks with exhaustive pattern matching:

switch (state.status) {
  case 'loading': return <Spinner />;
  case 'success': return <User data={state.data} />;
  case 'error': return <Error error={state.error} />;
}

The compiler now proves you've handled every case.

Step 6: Remove Defensive Checks

Delete runtime checks that TypeScript now guarantees:

// DELETE THIS:
if (state.status === 'success' && state.data) { ... }

// TypeScript already knows 'success' means data exists:
if (state.status === 'success') {
  state.data // ✓ guaranteed present
}

Common Refactoring Patterns

Multi-boolean collapse: Three booleans (isPending, isSaved, isFailed) become one discriminated union with three cases.

Optional dependency chains: If connectionId requires sessionToken, don't make both optional—create separate Connected and Disconnected types.

Empty collection edge cases: Instead of items: T[] that might be empty when it shouldn't be, use { status: 'empty' } | { status: 'populated'; items: [T, ...T[]] }.

The Refactoring Mindset

This isn't about perfection on the first try. It's iterative:

  1. Ship with simple types
  2. Notice bugs from impossible states
  3. Refactor one type at a time
  4. Let the compiler guide migration

Key Takeaway: Refactoring toward impossible states follows a repeatable pattern: identify invalid combinations → enumerate valid states → model as discriminated unions → update all construction and consumption sites → delete now-redundant runtime checks.