# TypeScript Migration Project Plan - Issue #6

## Executive Summary

**Project:** Migration of HTML Chess Game from JavaScript to TypeScript
**Scope:** 18 JavaScript modules (~3,700 lines of code) + 7 test files (~124 tests)
**Strategy:** Incremental, layer-by-layer migration with continuous integration
**Timeline:** 40-50 hours over 4-6 weeks
**Risk Level:** Medium (mitigated by incremental approach)

---

## 1. Project Overview

### 1.1 Current State Assessment

**Codebase Structure:**
```
js/
├── pieces/          # 8 files, ~800 lines (Piece base + 6 concrete pieces)
├── game/            # 2 files, ~450 lines (Board, GameState)
├── engine/          # 2 files, ~600 lines (MoveValidator, SpecialMoves)
├── controllers/     # 2 files, ~700 lines (GameController, DragDropHandler)
├── views/           # 1 file, ~400 lines (BoardRenderer)
├── utils/           # 3 files, ~500 lines (Constants, EventBus, Helpers)
└── main.js          # 1 file, ~250 lines (Entry point)

tests/
└── unit/
    ├── pieces/      # 7 test files
    └── game/        # 1 test file (Board.test.js)
```

**Test Coverage:** 124 passing tests (100% pass rate)

**Key Dependencies:**
- Jest testing framework with jsdom
- ESLint for linting
- ES6 modules
- No external runtime dependencies

### 1.2 Migration Goals

**Primary Objectives:**
1. ✅ Add strong type safety to prevent bugs
2. ✅ Improve developer experience with IntelliSense
3. ✅ Maintain 100% test pass rate throughout migration
4. ✅ Enable better refactoring capabilities
5. ✅ Improve code maintainability and documentation

**Success Criteria:**
- All JavaScript files converted to TypeScript
- Zero TypeScript compilation errors
- 100% test coverage maintained
- All 124 tests passing
- No runtime behavior changes
- Proper type definitions for all APIs

---

## 2. Migration Phases & Milestones

### Phase 0: Foundation & Setup (4-6 hours)
**Milestone:** TypeScript infrastructure ready

**Tasks:**
1. **Install TypeScript dependencies** (30 min)
   - Install typescript, @types/node, @types/jest
   - Install ts-jest for test support
   - Install @types/jsdom

2. **Create TypeScript configuration** (1 hour)
   - Create tsconfig.json with appropriate settings
   - Configure strict mode (strictNullChecks, noImplicitAny, etc.)
   - Set up source maps for debugging
   - Configure module resolution

3. **Update build tooling** (1 hour)
   - Configure ts-jest in jest.config.js
   - Update package.json scripts
   - Add TypeScript to ESLint configuration
   - Set up watch mode for development

4. **Create type definition files** (1.5 hours)
   - Create global.d.ts for custom types
   - Define Position, Color, PieceType interfaces
   - Create Move, GameResult type definitions
   - Document type conventions

5. **Validation & Testing** (1 hour)
   - Verify TypeScript compiler works
   - Test build pipeline
   - Ensure tests still run
   - Document setup for team

**Deliverables:**
- ✓ tsconfig.json
- ✓ jest.config.ts
- ✓ global.d.ts with core types
- ✓ Updated package.json
- ✓ Setup documentation

**Exit Criteria:**
- TypeScript compiles without errors (empty project)
- Jest runs with ts-jest
- Build scripts operational

---

### Phase 1: Core Type Definitions (6-8 hours)
**Milestone:** Foundation types and constants migrated

**Tasks:**
1. **Migrate utils/Constants.js → Constants.ts** (2 hours)
   - Convert all exports to typed constants
   - Create const assertions for literal types
   - Add readonly modifiers
   - Create union types for Colors, PieceTypes, GameStatus
   - Test: Verify all imports work correctly

2. **Migrate utils/Helpers.js → Helpers.ts** (2 hours)
   - Add type signatures to all helper functions
   - Use generics where appropriate
   - Add JSDoc comments with @param and @returns
   - Create utility types (e.g., Position, Coordinate)
   - Test: Verify helper function behavior unchanged

3. **Migrate utils/EventBus.js → EventBus.ts** (2-3 hours)
   - Create generic EventBus<T> class
   - Type event names as union type
   - Add type safety to event handlers
   - Create EventMap interface
   - Test: Verify event system works correctly

4. **Create shared type definitions** (1 hour)
   - types/chess.ts - Core chess types
   - types/game.ts - Game state types
   - types/ui.ts - UI-related types

**Deliverables:**
- ✓ src/utils/Constants.ts
- ✓ src/utils/Helpers.ts
- ✓ src/utils/EventBus.ts
- ✓ src/types/*.ts files

**Exit Criteria:**
- All utilities compile without errors
- Type inference works correctly
- Helper tests pass (adapted to TypeScript)

**Risk Assessment:**
- **Risk:** Breaking changes to constant usage
- **Mitigation:** Keep JS files temporarily, add .ts alongside
- **Rollback:** Revert to .js files if issues arise

---

### Phase 2: Game Models (8-10 hours)
**Milestone:** Core game logic typed

**Priority Order:** Board → Piece → Concrete Pieces

#### 2.1 Board Migration (3-4 hours)

**Tasks:**
1. **Create Board interface** (1 hour)
   - Define IBoard interface
   - Type grid as (Piece | null)[][]
   - Add method signatures with return types

2. **Migrate game/Board.js → Board.ts** (2-3 hours)
   - Convert class to implement IBoard
   - Add generic type parameters where needed
   - Type all method parameters and returns
   - Add null checks and type guards
   - Update imports for piece classes

**Testing:**
- Run Board.test.js (converted to .ts)
- Verify all board operations
- Check piece placement logic

#### 2.2 Piece Hierarchy (5-6 hours)

**Tasks:**
1. **Create Piece interfaces** (1 hour)
   - Define IPiece base interface
   - Create concrete piece interfaces
   - Add discriminated union for piece types

2. **Migrate pieces/Piece.js → Piece.ts** (2 hours)
   - Convert to abstract class
   - Add abstract method signatures
   - Type position as Position interface
   - Add type guards (isPawn, isKing, etc.)

3. **Migrate concrete pieces** (2-3 hours)
   - Pawn.ts (includes en passant logic)
   - Rook.ts (simpler sliding piece)
   - Bishop.ts (simpler sliding piece)
   - Knight.ts (L-shaped moves)
   - Queen.ts (combined sliding)
   - King.ts (includes castling)

**Migration Order:** Rook → Bishop → Knight → Queen → Pawn → King
(Simple to complex)

**Testing:**
- Run all piece test files
- Verify move generation
- Check capture mechanics
- Validate special moves

**Deliverables:**
- ✓ src/game/Board.ts
- ✓ src/pieces/Piece.ts
- ✓ src/pieces/*.ts (all 6 pieces)

**Exit Criteria:**
- All piece tests passing
- Board tests passing
- No TypeScript errors
- Type inference working in IDE

---

### Phase 3: Game Engine (8-10 hours)
**Milestone:** Game logic and validation typed

#### 3.1 GameState Migration (3-4 hours)

**Tasks:**
1. **Create GameState types** (1 hour)
   - Define GameStateData interface
   - Type move history
   - Type captured pieces arrays
   - Create GameStatus union type

2. **Migrate game/GameState.js → GameState.ts** (2-3 hours)
   - Type all state properties
   - Add type guards for state checks
   - Type move history with Move interface
   - Add readonly modifiers where appropriate

**Testing:**
- Verify game state transitions
- Check move history tracking
- Validate captured pieces tracking

#### 3.2 Move Validation (3-4 hours)

**Tasks:**
1. **Create Move types** (1 hour)
   - Define Move interface
   - Create MoveResult type
   - Add special move types (EnPassantMove, CastleMove, etc.)

2. **Migrate engine/MoveValidator.js → MoveValidator.ts** (2-3 hours)
   - Type all validation methods
   - Add type guards for move types
   - Create proper return types for validation
   - Add null safety checks

**Testing:**
- Run move validation tests
- Check check detection
- Verify checkmate detection
- Test stalemate conditions

#### 3.3 Special Moves (2-3 hours)

**Tasks:**
1. **Migrate engine/SpecialMoves.js → SpecialMoves.ts** (2-3 hours)
   - Type castling logic
   - Type en passant logic
   - Type pawn promotion
   - Add move type discriminators

**Testing:**
- Verify castling conditions
- Test en passant captures
- Check pawn promotion

**Deliverables:**
- ✓ src/game/GameState.ts
- ✓ src/engine/MoveValidator.ts
- ✓ src/engine/SpecialMoves.ts

**Exit Criteria:**
- All engine tests passing
- No type errors
- Logic behavior unchanged

---

### Phase 4: Controllers & Views (6-8 hours)
**Milestone:** UI layer typed

#### 4.1 BoardRenderer (2-3 hours)

**Tasks:**
1. **Create UI types** (30 min)
   - Define HTMLChessBoard interface
   - Type DOM element references
   - Create render options types

2. **Migrate views/BoardRenderer.js → BoardRenderer.ts** (1.5-2 hours)
   - Type all DOM operations
   - Add null checks for element queries
   - Type event handlers
   - Add proper this typing

**Testing:**
- Manual UI testing
- Verify rendering correctness
- Check highlight system

#### 4.2 DragDropHandler (2-3 hours)

**Tasks:**
1. **Create drag/drop types** (30 min)
   - Define DragState interface
   - Type drag event handlers
   - Create drop validation types

2. **Migrate controllers/DragDropHandler.js → DragDropHandler.ts** (1.5-2 hours)
   - Type all event handlers
   - Add null safety for dragged elements
   - Type coordinate calculations
   - Add proper event typing

**Testing:**
- Manual drag/drop testing
- Verify piece selection
- Check move execution

#### 4.3 GameController (2-3 hours)

**Tasks:**
1. **Migrate controllers/GameController.js → GameController.ts** (2-3 hours)
   - Type controller orchestration
   - Add type guards for game states
   - Type all public methods
   - Add proper dependency typing

**Testing:**
- Full integration testing
- Verify game flow
- Check all interactions

**Deliverables:**
- ✓ src/views/BoardRenderer.ts
- ✓ src/controllers/DragDropHandler.ts
- ✓ src/controllers/GameController.ts

**Exit Criteria:**
- Full game playable
- All UI interactions work
- No type errors
- Manual testing passed

---

### Phase 5: Entry Point & Tests (4-6 hours)
**Milestone:** Complete migration

#### 5.1 Main Entry Point (1-2 hours)

**Tasks:**
1. **Migrate main.js → main.ts** (1-2 hours)
   - Type application initialization
   - Add proper module loading
   - Type global exports if any
   - Update HTML script references

#### 5.2 Test Migration (3-4 hours)

**Tasks:**
1. **Convert test files to TypeScript** (2-3 hours)
   - Update imports to .ts extensions
   - Add type assertions where needed
   - Fix any type-related test issues
   - Update jest expectations

2. **Add type tests** (1 hour)
   - Create type-only tests
   - Verify type inference
   - Test discriminated unions
   - Check generic constraints

**Deliverables:**
- ✓ src/main.ts
- ✓ tests/**/*.test.ts
- ✓ Type-only tests

**Exit Criteria:**
- All 124 tests passing
- Full type coverage
- No compilation errors
- Game fully functional

---

### Phase 6: Optimization & Documentation (4-6 hours)
**Milestone:** Production-ready TypeScript codebase

**Tasks:**
1. **Type optimization** (2 hours)
   - Remove unnecessary type assertions
   - Add utility types for common patterns
   - Create branded types for IDs
   - Optimize type inference

2. **Documentation updates** (1-2 hours)
   - Update README with TypeScript info
   - Document type conventions
   - Create migration guide
   - Update API documentation

3. **Build optimization** (1 hour)
   - Configure production build
   - Set up source maps
   - Optimize compilation speed
   - Configure declaration file generation

4. **Final validation** (1 hour)
   - Run full test suite
   - Manual testing of all features
   - Performance testing
   - Code review

**Deliverables:**
- ✓ Optimized type definitions
- ✓ Updated documentation
- ✓ Production build configuration
- ✓ Migration guide

**Exit Criteria:**
- Zero TypeScript errors
- All tests passing
- Documentation complete
- Ready for production

---

## 3. Effort Estimates

### Total Time Breakdown

| Phase | Tasks | Estimated Hours | Optimistic | Pessimistic |
|-------|-------|----------------|------------|-------------|
| Phase 0: Foundation | Setup & Config | 4-6 | 4 | 8 |
| Phase 1: Core Types | Utils & Constants | 6-8 | 6 | 10 |
| Phase 2: Models | Board & Pieces | 8-10 | 8 | 12 |
| Phase 3: Engine | Logic & Validation | 8-10 | 8 | 12 |
| Phase 4: UI | Controllers & Views | 6-8 | 6 | 10 |
| Phase 5: Integration | Main & Tests | 4-6 | 4 | 8 |
| Phase 6: Polish | Optimization & Docs | 4-6 | 4 | 8 |
| **TOTAL** | | **40-54 hours** | **40 hours** | **68 hours** |

### Recommended Approach: 50% Contingency
**Baseline Estimate:** 47 hours (average)
**With Contingency:** 70 hours (50% buffer)

---

## 4. Critical Path Analysis

### Dependencies Map

```
Phase 0 (Foundation)
    ↓
Phase 1 (Core Types)
    ↓
Phase 2 (Models) ← CRITICAL PATH STARTS
    ↓
Phase 3 (Engine) ← CRITICAL PATH
    ↓
Phase 4 (UI)
    ↓
Phase 5 (Integration)
    ↓
Phase 6 (Polish)
```

### Critical Path Items (Must be sequential)

1. **Foundation Setup** → Cannot proceed without TypeScript tooling
2. **Constants/Types** → Required by all other modules
3. **Piece Base Class** → Required by all concrete pieces
4. **Board Class** → Required by game logic
5. **GameState** → Required by controllers
6. **MoveValidator** → Required by controllers
7. **Controllers** → Required for integration
8. **Main Entry** → Final integration point

### Parallel Opportunities

**Can be done in parallel:**
- Concrete piece migrations (after Piece.ts)
- Test file conversions (alongside source)
- Documentation updates (throughout)
- UI components (BoardRenderer + DragDropHandler)

**Parallelization Strategy:**
- 2 developers: 30-35 hours each (vs 47 solo)
- 3 developers: 20-25 hours each

---

## 5. Risk Assessment & Mitigation

### Risk Register

| # | Risk | Probability | Impact | Severity | Mitigation | Contingency |
|---|------|-------------|--------|----------|------------|-------------|
| R1 | Type errors break existing code | Medium | High | **HIGH** | Incremental migration, keep .js files | Rollback to .js files |
| R2 | Tests fail after migration | Medium | High | **HIGH** | Migrate tests alongside source | Fix type issues, revert if needed |
| R3 | Breaking API changes | Low | High | **MEDIUM** | Maintain backwards compatibility | Create adapter layer |
| R4 | Scope creep (refactoring) | High | Medium | **HIGH** | Strict "no refactoring" policy | Time-box refactoring to Phase 6 |
| R5 | DOM type issues (jsdom) | Medium | Medium | **MEDIUM** | Use proper @types packages | Add custom type definitions |
| R6 | Generic type complexity | Medium | Low | **LOW** | Keep types simple initially | Add advanced types later |
| R7 | Build pipeline issues | Low | Medium | **LOW** | Test tooling early (Phase 0) | Have fallback build config |
| R8 | Developer learning curve | Medium | Medium | **MEDIUM** | Provide TypeScript training | Pair programming |
| R9 | IDE performance issues | Low | Low | **LOW** | Configure tsconfig properly | Adjust strict settings |
| R10 | Third-party type definitions | Low | Medium | **LOW** | Verify all @types exist | Write custom .d.ts files |

### High-Priority Risks (Detailed Mitigation)

#### R1: Type Errors Break Existing Code
**Mitigation Strategy:**
1. Keep `.js` and `.ts` files side-by-side temporarily
2. Use `// @ts-expect-error` comments for known issues
3. Migrate in complete module units
4. Run full test suite after each module
5. Use feature flags to toggle old/new code

**Rollback Plan:**
1. Revert last commit
2. Switch imports back to .js
3. Investigate issue offline
4. Fix and retry

#### R4: Scope Creep
**Prevention:**
- Document "migration only, no refactoring" rule
- Defer refactoring ideas to Phase 6 or post-migration
- Code review focuses on equivalence, not improvement
- Create separate issues for refactoring opportunities

**Example:**
❌ DON'T: "Let's make Piece.getValidMoves() return a Set instead of Array"
✅ DO: "Convert return type to Position[], note in TODO for future optimization"

---

## 6. Migration Strategy: Incremental vs. Big Bang

### Recommendation: **INCREMENTAL MIGRATION** ✅

### Incremental Approach (RECOMMENDED)

**Process:**
1. Add TypeScript alongside JavaScript
2. Migrate one module at a time
3. Keep game working at all times
4. Remove .js files after validation

**Advantages:**
- ✅ Lower risk - can rollback individual modules
- ✅ Continuous integration - game always works
- ✅ Can ship features during migration
- ✅ Easy to track progress
- ✅ Better for team collaboration
- ✅ Learn TypeScript incrementally

**Disadvantages:**
- ❌ Longer total time (need both .js and .ts temporarily)
- ❌ Need to handle mixed .js/.ts imports
- ❌ More complex build configuration
- ❌ Risk of inconsistency

**Best For:**
- Active projects with ongoing development
- Teams learning TypeScript
- Projects with high uptime requirements
- Large codebases (>5,000 lines)

### Big Bang Approach (NOT RECOMMENDED)

**Process:**
1. Create feature branch
2. Convert all files at once
3. Fix all issues
4. Merge when complete

**Advantages:**
- ✅ Faster total time
- ✅ Cleaner - no mixed .js/.ts
- ✅ Simpler build config
- ✅ Consistent codebase immediately

**Disadvantages:**
- ❌ HIGH RISK - all or nothing
- ❌ Game broken for weeks
- ❌ Hard to rollback
- ❌ Difficult code reviews (massive PR)
- ❌ Merge conflicts if team works on features
- ❌ No production deployments during migration

**Best For:**
- Small codebases (<2,000 lines)
- Projects in maintenance mode
- Solo developers
- No time pressure

### Our Recommendation: Incremental with Milestones

**Migration Flow:**
```
Week 1: Phase 0-1 (Setup + Core Types)
  ↓ [Checkpoint: Build works, utils typed]
Week 2: Phase 2 (Models)
  ↓ [Checkpoint: Pieces work, tests pass]
Week 3: Phase 3 (Engine)
  ↓ [Checkpoint: Game logic works]
Week 4: Phase 4 (UI)
  ↓ [Checkpoint: Full game playable]
Week 5: Phase 5-6 (Integration + Polish)
  ↓ [Checkpoint: Production ready]
```

**Weekly Validation:**
- Run full test suite
- Manual game testing
- Performance check
- Type coverage report

---

## 7. Success Criteria by Phase

### Phase 0: Foundation
- [ ] TypeScript compiles without errors
- [ ] Jest configured with ts-jest
- [ ] All existing tests still pass
- [ ] Build scripts work
- [ ] Source maps generated

### Phase 1: Core Types
- [ ] Constants fully typed
- [ ] Helpers have type signatures
- [ ] EventBus generic and type-safe
- [ ] No `any` types used
- [ ] Type inference works in IDE

### Phase 2: Models
- [ ] Board class fully typed
- [ ] All 6 piece classes typed
- [ ] Piece hierarchy correct
- [ ] All piece tests passing
- [ ] Move generation typed

### Phase 3: Engine
- [ ] GameState fully typed
- [ ] MoveValidator typed
- [ ] SpecialMoves typed
- [ ] Check/checkmate detection works
- [ ] All game rules enforced

### Phase 4: UI
- [ ] BoardRenderer typed
- [ ] DragDropHandler typed
- [ ] GameController typed
- [ ] All DOM operations safe
- [ ] Full game playable

### Phase 5: Integration
- [ ] All source files are .ts
- [ ] All test files are .ts
- [ ] 124 tests passing
- [ ] No compilation errors
- [ ] No runtime errors

### Phase 6: Polish
- [ ] Type coverage >95%
- [ ] Documentation updated
- [ ] Build optimized
- [ ] Performance validated
- [ ] Ready for production

---

## 8. Rollback Strategies

### Module-Level Rollback
**When:** Single module causes issues

**Process:**
1. Revert module to .js version
2. Update imports to use .js extension
3. Continue with other modules
4. Retry problem module later

**Example:**
```bash
# Rollback Board.ts to Board.js
git checkout HEAD -- js/game/Board.js
rm -f js/game/Board.ts
# Update imports in dependent files
# Continue with other migrations
```

### Phase-Level Rollback
**When:** Entire phase is problematic

**Process:**
1. Revert to previous phase checkpoint
2. Re-evaluate approach
3. Adjust plan
4. Restart phase with new strategy

### Complete Rollback
**When:** Fundamental issues discovered

**Process:**
1. Revert to pre-migration state
2. Keep TypeScript config for future
3. Re-evaluate project readiness
4. Create new migration plan

**Rollback Decision Matrix:**

| Issue | Severity | Response |
|-------|----------|----------|
| Single type error | Low | Fix immediately |
| Module incompatibility | Medium | Module rollback |
| Multiple test failures | High | Phase rollback |
| Build system broken | Critical | Complete rollback |
| Performance degradation | High | Investigate + rollback |

---

## 9. Developer Guide

### 9.1 Getting Started

**Prerequisites:**
- Node.js 16+
- npm 8+
- TypeScript knowledge (basic)
- Git

**Initial Setup:**
```bash
# Pull latest code
git pull origin main

# Install dependencies
npm install

# Verify TypeScript works
npx tsc --version

# Run tests
npm test

# Start development server
npm run dev
```

### 9.2 Migration Workflow

**For Each Module:**

1. **Create TypeScript file**
```bash
# Create .ts version alongside .js
cp js/pieces/Pawn.js js/pieces/Pawn.ts
```

2. **Add types incrementally**
```typescript
// Start with basic types
export class Pawn extends Piece {
    constructor(color: string, position: Position) {
        super(color, position);
    }

    // Add return type
    getValidMoves(board: Board): Position[] {
        // Implementation
    }
}
```

3. **Run type checker**
```bash
# Check for errors
npx tsc --noEmit
```

4. **Update imports**
```typescript
// Change imports to use .ts
import { Pawn } from './pieces/Pawn.ts';
```

5. **Run tests**
```bash
npm test -- Pawn.test.ts
```

6. **Remove .js file**
```bash
# Only after validation
rm js/pieces/Pawn.js
```

### 9.3 TypeScript Best Practices

**DO:**
✅ Use `interface` for object shapes
✅ Use `type` for unions and primitives
✅ Enable strict mode
✅ Add explicit return types
✅ Use const assertions
✅ Leverage type inference
✅ Use generics for reusable code
✅ Add JSDoc comments

**DON'T:**
❌ Use `any` type (use `unknown` instead)
❌ Use `as` casts (use type guards)
❌ Disable strict checks
❌ Over-engineer types initially
❌ Refactor logic during migration
❌ Ignore type errors with comments
❌ Use non-null assertion (`!`) unnecessarily

### 9.4 Common Patterns

**Pattern 1: Type Guards**
```typescript
function isPawn(piece: Piece): piece is Pawn {
    return piece.type === 'pawn';
}

// Usage
if (isPawn(piece)) {
    // TypeScript knows piece is Pawn here
    piece.enPassantTarget;
}
```

**Pattern 2: Discriminated Unions**
```typescript
type Move =
    | { type: 'normal'; from: Position; to: Position }
    | { type: 'castle'; side: 'kingside' | 'queenside' }
    | { type: 'enPassant'; from: Position; to: Position; captured: Position };

function executeMove(move: Move) {
    switch (move.type) {
        case 'normal':
            // Move properties available here
            break;
        case 'castle':
            // Castle properties available here
            break;
    }
}
```

**Pattern 3: Utility Types**
```typescript
// Make all properties readonly
type ReadonlyBoard = Readonly<Board>;

// Pick specific properties
type PositionOnly = Pick<Piece, 'position'>;

// Make properties optional
type PartialPiece = Partial<Piece>;
```

### 9.5 Testing TypeScript Code

**Test File Example:**
```typescript
// Pawn.test.ts
import { Pawn } from '../../src/pieces/Pawn';
import { Board } from '../../src/game/Board';
import type { Position } from '../../src/types/chess';

describe('Pawn', () => {
    let board: Board;
    let pawn: Pawn;

    beforeEach(() => {
        board = new Board();
        pawn = new Pawn('white', { row: 6, col: 4 });
    });

    it('can move forward one square', () => {
        const moves: Position[] = pawn.getValidMoves(board);
        expect(moves).toContainEqual({ row: 5, col: 4 });
    });
});
```

**Type-Only Tests:**
```typescript
// types.test.ts
import { expectType } from 'tsd';
import type { Piece, Position } from '../src/types/chess';

// Test type inference
const pos: Position = { row: 0, col: 0 };
expectType<Position>(pos);

// Test generic constraints
function movePiece<T extends Piece>(piece: T): T {
    return piece;
}
```

### 9.6 Troubleshooting

**Problem:** `Cannot find module` errors
**Solution:** Check import paths, add .ts extension if needed

**Problem:** `Type 'null' is not assignable to type 'Piece'`
**Solution:** Use union type `Piece | null` or add null check

**Problem:** `Property does not exist on type`
**Solution:** Add type guard or use optional chaining `?.`

**Problem:** Tests fail with "Cannot use import statement"
**Solution:** Verify jest.config.ts uses ts-jest

**Problem:** IDE performance slow
**Solution:** Configure `exclude` in tsconfig.json to skip node_modules

---

## 10. Timeline Recommendations

### Aggressive Timeline (4 weeks)
**Full-time dedication (40 hrs/week)**

```
Week 1: Phases 0-1 (Foundation + Core Types)
  Mon-Tue: Setup (8h)
  Wed-Fri: Utils migration (12h)

Week 2: Phase 2 (Models)
  Mon-Wed: Board + Piece base (15h)
  Thu-Fri: Concrete pieces (10h)

Week 3: Phase 3-4 (Engine + UI)
  Mon-Tue: GameState + Validators (10h)
  Wed-Fri: Controllers + Views (15h)

Week 4: Phase 5-6 (Integration + Polish)
  Mon-Tue: Integration (10h)
  Wed-Fri: Testing + Documentation (15h)
```

### Balanced Timeline (6 weeks)
**Part-time work (15-20 hrs/week)**

```
Week 1-2: Phase 0-1 (Setup + Foundation)
  - Setup TypeScript environment
  - Migrate utilities
  - Checkpoint: Build works

Week 3-4: Phase 2-3 (Models + Engine)
  - Migrate pieces and board
  - Migrate game logic
  - Checkpoint: Game logic works

Week 5: Phase 4 (UI)
  - Migrate controllers
  - Migrate views
  - Checkpoint: Full game works

Week 6: Phase 5-6 (Integration + Polish)
  - Final integration
  - Documentation
  - Checkpoint: Production ready
```

### Conservative Timeline (8-10 weeks)
**Spare time work (5-10 hrs/week)**

```
Weeks 1-2: Phase 0
Weeks 3-4: Phase 1
Weeks 5-6: Phase 2
Weeks 7-8: Phase 3-4
Weeks 9-10: Phase 5-6
```

### Recommended: **6-Week Balanced Timeline**

**Rationale:**
- Allows for learning curve
- Time for code review
- Handles unexpected issues
- Sustainable pace
- Can still ship features

---

## 11. Appendices

### A. TypeScript Configuration

**Recommended tsconfig.json:**
```json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ES2020",
    "lib": ["ES2020", "DOM"],
    "outDir": "./dist",
    "rootDir": "./js",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "declaration": true,
    "declarationMap": true,
    "sourceMap": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true
  },
  "include": ["js/**/*"],
  "exclude": ["node_modules", "dist", "tests"]
}
```

### B. Jest Configuration

**jest.config.ts:**
```typescript
import type { Config } from '@jest/types';

const config: Config.InitialOptions = {
  preset: 'ts-jest',
  testEnvironment: 'jsdom',
  roots: ['<rootDir>/tests'],
  testMatch: ['**/*.test.ts'],
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
  collectCoverageFrom: [
    'js/**/*.{ts,tsx}',
    '!js/**/*.d.ts',
  ],
  coverageThreshold: {
    global: {
      branches: 80,
      functions: 80,
      lines: 80,
      statements: 80
    }
  }
};

export default config;
```

### C. Package.json Updates

```json
{
  "scripts": {
    "build": "tsc",
    "build:watch": "tsc --watch",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:coverage": "jest --coverage",
    "type-check": "tsc --noEmit",
    "lint": "eslint 'js/**/*.{ts,tsx}'",
    "format": "prettier --write \"**/*.{ts,tsx,css,html}\""
  },
  "devDependencies": {
    "@types/jest": "^29.5.0",
    "@types/node": "^20.0.0",
    "@typescript-eslint/eslint-plugin": "^6.0.0",
    "@typescript-eslint/parser": "^6.0.0",
    "ts-jest": "^29.1.0",
    "typescript": "^5.3.0"
  }
}
```

### D. Type Definitions Template

**types/chess.ts:**
```typescript
// Core chess types

export type Color = 'white' | 'black';

export type PieceType = 'pawn' | 'knight' | 'bishop' | 'rook' | 'queen' | 'king';

export interface Position {
    row: number;
    col: number;
}

export interface Move {
    from: Position;
    to: Position;
    piece: PieceType;
    captured?: PieceType;
    promotion?: PieceType;
    castling?: 'kingside' | 'queenside';
    enPassant?: boolean;
}

export interface GameStatus {
    status: 'active' | 'check' | 'checkmate' | 'stalemate' | 'draw';
    winner?: Color;
    reason?: string;
}
```

### E. Progress Tracking Template

**migration-progress.md:**
```markdown
# TypeScript Migration Progress

## Phase 0: Foundation ✅/❌
- [ ] TypeScript installed
- [ ] tsconfig.json created
- [ ] Jest configured
- [ ] Build scripts working

## Phase 1: Core Types (0/3)
- [ ] Constants.ts
- [ ] Helpers.ts
- [ ] EventBus.ts

## Phase 2: Models (0/8)
- [ ] Board.ts
- [ ] Piece.ts
- [ ] Pawn.ts
- [ ] Rook.ts
- [ ] Bishop.ts
- [ ] Knight.ts
- [ ] Queen.ts
- [ ] King.ts

[Continue for all phases...]

## Test Status
- Total Tests: 124
- Passing: X/124
- Failing: X/124

## Current Blockers
1. [List any blockers]
```

### F. Code Review Checklist

**For each migrated module:**
- [ ] No `any` types used
- [ ] All function signatures typed
- [ ] Proper use of `null` vs `undefined`
- [ ] Type guards for unions
- [ ] No type assertions without justification
- [ ] JSDoc comments preserved
- [ ] Tests still passing
- [ ] No logic changes
- [ ] Performance unchanged
- [ ] No console errors

---

## 12. Conclusion

### Summary

This TypeScript migration plan provides a comprehensive, incremental approach to converting the HTML Chess Game from JavaScript to TypeScript while maintaining full functionality throughout the process.

**Key Success Factors:**
1. ✅ Incremental approach minimizes risk
2. ✅ Clear phases with defined deliverables
3. ✅ Comprehensive testing at each stage
4. ✅ Rollback strategies for each level
5. ✅ Realistic time estimates with contingency
6. ✅ Focus on type safety without refactoring

**Expected Outcomes:**
- Type-safe codebase with better maintainability
- Improved developer experience with IntelliSense
- Better refactoring capabilities
- Same functionality, enhanced quality
- Foundation for future improvements

**Next Steps:**
1. Review and approve this plan
2. Set up TypeScript environment (Phase 0)
3. Begin incremental migration (Phase 1)
4. Hold weekly checkpoints
5. Adjust plan based on learnings

### Approval Sign-off

- [ ] Plan reviewed by development team
- [ ] Timeline agreed upon
- [ ] Resources allocated
- [ ] Risks acknowledged
- [ ] Ready to begin Phase 0

---

**Document Version:** 1.0
**Last Updated:** 2025-11-23
**Author:** Strategic Planning Agent
**Status:** Ready for Review
