# TypeScript Migration - Quick Reference Card

## 📋 At a Glance

**Total Time:** 40-54 hours (6 weeks recommended)
**Files:** 18 modules + 7 test files
**Strategy:** Incremental migration
**Risk:** Medium (mitigated)

---

## 🎯 Phase Checklist

### Phase 0: Foundation (4-6h)
```bash
npm install typescript ts-jest @types/jest @types/node
npx tsc --init
```
- [ ] TypeScript installed
- [ ] tsconfig.json created
- [ ] Jest configured
- [ ] Build scripts working

### Phase 1: Core Types (6-8h)
- [ ] Constants.ts
- [ ] Helpers.ts
- [ ] EventBus.ts

### Phase 2: Models (8-10h)
- [ ] Board.ts ← START HERE
- [ ] Piece.ts ← THEN THIS
- [ ] Rook, Bishop, Knight, Queen
- [ ] Pawn, King

### Phase 3: Engine (8-10h)
- [ ] GameState.ts
- [ ] MoveValidator.ts
- [ ] SpecialMoves.ts

### Phase 4: UI (6-8h)
- [ ] BoardRenderer.ts
- [ ] DragDropHandler.ts
- [ ] GameController.ts

### Phase 5: Integration (4-6h)
- [ ] main.ts
- [ ] All tests → .ts

### Phase 6: Polish (4-6h)
- [ ] Optimize types
- [ ] Documentation
- [ ] Production build

---

## 🚀 Quick Start Commands

```bash
# Setup (Phase 0)
npm install --save-dev typescript ts-jest @types/jest @types/node

# Create config
npx tsc --init

# Build
npm run build

# Test
npm test

# Type check only
npx tsc --noEmit

# Watch mode
npm run build:watch
```

---

## 📝 Migration Workflow (Per Module)

### 1. Create .ts file
```bash
cp js/pieces/Pawn.js js/pieces/Pawn.ts
```

### 2. Add types
```typescript
export class Pawn extends Piece {
    constructor(color: Color, position: Position) {
        super(color, position);
    }

    getValidMoves(board: Board): Position[] {
        // ...
    }
}
```

### 3. Type check
```bash
npx tsc --noEmit
```

### 4. Update imports
```typescript
import { Pawn } from './pieces/Pawn.ts';
```

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

### 6. Remove .js
```bash
rm js/pieces/Pawn.js
```

---

## ✅ Success Criteria

### Each Phase
- [ ] Zero compilation errors
- [ ] All tests passing
- [ ] No `any` types
- [ ] Type inference working

### Overall
- [ ] 124/124 tests passing
- [ ] Type coverage >95%
- [ ] Game fully functional
- [ ] Production ready

---

## 🔴 Red Flags → Stop & Reassess

- 🚨 >3 modules need rollback
- 🚨 Test pass rate <90%
- 🚨 Build time >5x increase
- 🚨 Timeline >50% over estimate

---

## ⚡ Common Patterns

### Type Guard
```typescript
function isPawn(piece: Piece): piece is Pawn {
    return piece.type === 'pawn';
}
```

### Discriminated Union
```typescript
type Move =
    | { type: 'normal'; from: Position; to: Position }
    | { type: 'castle'; side: 'kingside' | 'queenside' };
```

### Interface
```typescript
interface Position {
    row: number;
    col: number;
}
```

### Type Alias
```typescript
type Color = 'white' | 'black';
type PieceType = 'pawn' | 'rook' | 'knight' | 'bishop' | 'queen' | 'king';
```

---

## 🛡️ Type Safety Rules

### DO ✅
- Use `interface` for objects
- Use `type` for unions
- Enable strict mode
- Add return types explicitly
- Use const assertions
- Leverage inference

### DON'T ❌
- Use `any` (use `unknown`)
- Use `as` casts (use guards)
- Disable strict checks
- Use `!` non-null assertion
- Refactor during migration
- Ignore errors with comments

---

## 🔧 Troubleshooting

### "Cannot find module"
```typescript
// Add .ts extension
import { Piece } from './pieces/Piece.ts';
```

### "Type 'null' not assignable"
```typescript
// Use union type
function getPiece(row: number, col: number): Piece | null {
    return this.grid[row][col];
}
```

### "Property does not exist"
```typescript
// Add type guard or optional chaining
if (piece && isPawn(piece)) {
    piece.enPassantTarget; // OK
}

// Or use optional chaining
piece?.enPassantTarget;
```

### Tests fail with import errors
```javascript
// Update jest.config.ts
module.exports = {
    preset: 'ts-jest',
    testEnvironment: 'jsdom',
};
```

---

## 📊 Progress Tracking

### Weekly Metrics
```markdown
Week X:
- Files: X/18 (X%)
- Tests: X/124 (X%)
- Type Coverage: X%
- Hours: X/47
- Confidence: High/Med/Low
```

---

## 🎯 Critical Path

**Must be sequential:**
1. Phase 0: Setup (4-6h)
2. Phase 1: Types (6-8h)
3. Board.ts (3-4h)
4. Piece.ts (2h)
5. GameState.ts (3-4h)
6. MoveValidator.ts (2-3h)
7. main.ts (1-2h)

**Can be parallel:**
- Concrete pieces (after Piece.ts)
- UI components
- Test files
- Documentation

---

## 📅 Timeline Options

### Conservative (8-10 weeks)
- 5-10h/week
- Low stress, maximum learning
- Best for: Side projects

### Balanced (6 weeks) ⭐ RECOMMENDED
- 15-20h/week
- Sustainable pace
- Best for: Most projects

### Aggressive (4 weeks)
- 40h/week
- High intensity
- Best for: Urgent migrations

---

## 🆘 Emergency Contacts

### Rollback Procedure
```bash
# Module-level rollback
git checkout HEAD -- js/path/to/Module.js
rm js/path/to/Module.ts

# Phase-level rollback
git reset --hard <checkpoint-tag>

# Complete rollback
git reset --hard pre-migration
```

### Decision Matrix
| Issue | Response |
|-------|----------|
| Single type error | Fix immediately |
| Module incompatible | Module rollback |
| Multiple test failures | Phase rollback |
| Build broken | Complete rollback |

---

## 📚 Resources

### Documentation
- TypeScript: https://www.typescriptlang.org/docs/
- ts-jest: https://kulshekhar.github.io/ts-jest/
- Full plan: `docs/typescript-migration-plan.md`

### Project Files
- Detailed plan: `typescript-migration-plan.md`
- Timeline: `typescript-migration-timeline.md`
- Summary: `typescript-migration-summary.md`

---

## 🎓 TypeScript Essentials

### Basic Types
```typescript
let name: string = "Chess";
let age: number = 42;
let isActive: boolean = true;
let items: string[] = ['a', 'b'];
let tuple: [string, number] = ['a', 1];
```

### Function Types
```typescript
function add(a: number, b: number): number {
    return a + b;
}

const multiply = (a: number, b: number): number => a * b;
```

### Interfaces
```typescript
interface Piece {
    color: Color;
    position: Position;
    getValidMoves(board: Board): Position[];
}
```

### Type Aliases
```typescript
type Color = 'white' | 'black';
type Position = { row: number; col: number };
```

### Generics
```typescript
function first<T>(arr: T[]): T {
    return arr[0];
}
```

### Union Types
```typescript
type Result = Success | Error;
function getPiece(): Piece | null { }
```

### Intersection Types
```typescript
type Named = { name: string };
type Aged = { age: number };
type Person = Named & Aged;
```

---

## 🏁 Start Checklist

### Before Starting
- [ ] Read full plan
- [ ] Get team approval
- [ ] Allocate time
- [ ] Set up checkpoints
- [ ] Choose timeline

### Week 1
- [ ] Install dependencies
- [ ] Create configs
- [ ] Migrate utils
- [ ] First checkpoint

### Go Live
- [ ] All tests passing
- [ ] Zero type errors
- [ ] Documentation updated
- [ ] Performance validated
- [ ] Deploy to production

---

## 💡 Pro Tips

1. **Start small** - utils first, complex last
2. **Test frequently** - after each module
3. **No refactoring** - migration only
4. **Use strict mode** - catch more bugs
5. **Pair program** - learn together
6. **Time box work** - escalate if stuck
7. **Track progress** - weekly metrics
8. **Celebrate milestones** - stay motivated

---

## 📌 Key Files

### Configuration
- `tsconfig.json` - TypeScript settings
- `jest.config.ts` - Test configuration
- `package.json` - Scripts and deps

### Types
- `src/types/chess.ts` - Core types
- `src/types/game.ts` - Game types
- `src/types/ui.ts` - UI types
- `global.d.ts` - Global declarations

### Migration Order
```
1. Constants.ts     (2h)
2. Helpers.ts       (2h)
3. EventBus.ts      (2-3h)
4. Board.ts         (3-4h) ← CRITICAL
5. Piece.ts         (2h)   ← CRITICAL
6. Rook/Bishop      (1.5h)
7. Knight/Queen     (1.5h)
8. Pawn/King        (3h)
9. GameState.ts     (3-4h) ← CRITICAL
10. MoveValidator   (2-3h) ← CRITICAL
11. SpecialMoves    (2-3h)
12. BoardRenderer   (2h)
13. DragDropHandler (2h)
14. GameController  (2-3h)
15. main.ts         (1-2h)
16. Tests           (3-4h)
```

---

## 🎯 This Week's Focus

### Week 1: Foundation
**Goal:** TypeScript infrastructure ready
**Deliverable:** Utils typed, build works
**Time:** 10-14 hours

### Week 2: Models
**Goal:** Core game objects typed
**Deliverable:** Board + Pieces working
**Time:** 10-12 hours

### Week 3: Engine
**Goal:** Game logic typed
**Deliverable:** Rules enforced
**Time:** 12-14 hours

### Week 4: UI
**Goal:** Interface typed
**Deliverable:** Game playable
**Time:** 10-12 hours

### Week 5: Integration
**Goal:** Everything connected
**Deliverable:** All tests passing
**Time:** 8-10 hours

### Week 6: Polish
**Goal:** Production ready
**Deliverable:** Ship it!
**Time:** 8-10 hours

---

## 🔄 Daily Routine

### Morning (2h)
1. Review yesterday's work
2. Run tests
3. Start new module
4. Type check frequently

### Afternoon (2h)
1. Continue migration
2. Update tests
3. Run full test suite
4. Document blockers

### End of Day
1. Commit progress
2. Update tracking
3. Plan tomorrow
4. Ask for help if stuck

---

**Print this card and keep it handy during migration!**

Version 1.0 | Updated: 2025-11-23
