# Lint Troubleshooting Guide

Quick reference for common lint errors and how to fix them fast.

**Last Updated**: 2025-10-20 (Issue #159 - Documentation & Rollout)

---

## Table of Contents

- [TypeScript/ESLint Errors](#typescripteslint-errors)
- [Build Errors](#build-errors)
- [CI/CD Failures](#cicd-failures)
- [Pre-commit Hook Issues](#pre-commit-hook-issues)
- [Performance Issues](#performance-issues)
- [Getting More Help](#getting-more-help)

---

## TypeScript/ESLint Errors

### `@typescript-eslint/no-explicit-any`

**Error**: `Unexpected any. Specify a different type.`

**Quick Fixes**:

```typescript
// Option 1: Use specific interface/type
interface ResponseData {
  id: string;
  value: number;
}
const data: ResponseData = response.data;

// Option 2: Use unknown + type guard
const data: unknown = response.data;
if (isValidData(data)) {
  // data is now typed safely
}

// Option 3: Generic object type
const data: Record<string, unknown> = response.data;

// Option 4: Exception with justification (last resort)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Legacy API contract, see #123
const data: any = legacyAPI();
```

**When to use each**:
- **Option 1**: When you know the exact structure (preferred)
- **Option 2**: When structure is dynamic but needs validation
- **Option 3**: When working with key-value pairs of unknown values
- **Option 4**: Only when dealing with truly untyped third-party APIs

---

### `@typescript-eslint/no-unused-vars`

**Error**: `'variableName' is declared but its value is never read.`

**Quick Fixes**:

```typescript
// Option 1: Remove it
// Before
import { useState, useEffect } from 'react';
// After (if useEffect is unused)
import { useState } from 'react';

// Option 2: Prefix with underscore
// Before
function handler(req, res) {
  return req.body; // res never used
}
// After
function handler(req, _res) {
  return req.body;
}

// Option 3: Destructure only what's needed
// Before
const [state, setState] = useState(0);  // setState never used
// After
const [state] = useState(0);

// Option 4: Remove unused parameters (if not required by interface)
// Before
function onClick(event: MouseEvent) {
  doSomething(); // event never used
}
// After
function onClick() {
  doSomething();
}
```

**Pattern**: Prefix with `_` when variable is needed for interface compliance but not used.

---

### `@typescript-eslint/no-floating-promises`

**Error**: `Promises must be awaited, end with a call to .catch, end with a call to .then with a rejection handler or be explicitly marked as ignored with the 'void' operator.`

**Quick Fixes**:

```typescript
// Option 1: Await it (preferred)
async function processData() {
  await riskyAsyncOperation();
}

// Option 2: Void it (fire-and-forget, intentional)
async function processData() {
  void riskyAsyncOperation();
  // Continues immediately, doesn't wait for completion
}

// Option 3: Handle with .catch()
async function processData() {
  riskyAsyncOperation().catch(err => {
    console.error('Background task failed:', err);
  });
}

// Option 4: Handle with .then()
async function processData() {
  riskyAsyncOperation()
    .then(() => console.log('Done'))
    .catch(err => console.error('Failed:', err));
}
```

**Common mistake**:
```typescript
// ❌ BAD
daily?.join(); // Promise ignored

// ✅ GOOD
void daily?.join(); // Explicitly fire-and-forget
```

---

### `@typescript-eslint/no-misused-promises`

**Error**: `Promise returned in function argument where a void return was expected.` or `Promise-returning function provided to attribute where a void return was expected.`

**Quick Fixes**:

```typescript
// Express Routes - Use IIFE pattern
// Before (error)
app.post('/api/data', async (req, res) => {
  await processData(req.body);
  res.json({ ok: true });
});

// After (fixed)
app.post('/api/data', (req, res) => void (async () => {
  await processData(req.body);
  res.json({ ok: true });
})());

// Event Handlers - Use IIFE pattern
// Before (error)
button.addEventListener('click', async () => {
  await doWork();
});

// After (fixed)
button.addEventListener('click', () => void (async () => {
  await doWork();
})());

// React Event Handlers
// Before (error)
<button onClick={async () => await handleClick()}>Click</button>

// After (fixed)
<button onClick={() => void handleClick()}>Click</button>
```

**Pattern**: `(args) => void (async () => { ... })()`

---

### `@typescript-eslint/await-thenable`

**Error**: `Unexpected 'await' of a non-Promise (non-"Thenable") value.`

**Quick Fixes**:

```typescript
// Before (error)
await emit('event', data); // emit() returns void, not Promise

// After (fixed)
emit('event', data); // No await needed

// Before (error)
const value = await 42; // 42 is not a Promise

// After (fixed)
const value = 42;

// Before (error)
await someObject.syncMethod(); // Method is sync

// After (fixed)
someObject.syncMethod();
```

**How to identify**: If the function/method doesn't return a Promise, don't `await` it.

---

## Build Errors

### "Type error: Cannot find module..."

**Cause**: Lint fixes removed an import, or Nx cache is stale

**Fixes**:

```bash
# 1. Clear Nx cache
pnpm nx reset

# 2. Reinstall dependencies (if needed)
pnpm install

# 3. Rebuild from scratch
pnpm nx build <project-name> --skip-nx-cache

# 4. Check for missing imports
# Look at the error message and add the import back if needed
```

### "Property does not exist on type..."

**Cause**: Type was changed during lint fixes, accessing wrong property

**Fixes**:

```typescript
// Check the actual interface/type definition
// Option 1: Fix property name typo
obj.userName // if type has 'userName', not 'username'

// Option 2: Add type assertion (if you know better)
(obj as SpecificType).propertyName

// Option 3: Use optional chaining (if property may not exist)
obj.property?.subProperty
```

### "Cannot assign to 'x' because it is a read-only property"

**Cause**: TypeScript strict mode catches mutation of read-only properties

**Fixes**:

```typescript
// Option 1: Create new object instead of mutating
const newObj = { ...oldObj, property: newValue };

// Option 2: Use proper setState/update method
setState({ ...state, property: newValue });

// Option 3: If genuinely need mutation, cast (rare)
(obj as Mutable<typeof obj>).property = value;
```

---

## CI/CD Failures

### "Lint job failed with exit code 1"

**Diagnosis**:

```bash
# Run locally to see exact errors
pnpm nx run-many --target=lint --all --max-warnings=0

# Check specific project
pnpm nx lint <project-name>

# See affected projects
pnpm nx affected:lint
```

**Common causes**:
1. New `any` type introduced
2. Unused import added
3. Floating promise in new code
4. Merge conflict introduced lint error

**Fix**: Address the specific errors shown, then push again

### "Pre-commit hook blocked my commit"

**Diagnosis**:

```bash
# See what failed
git status # Check what files are staged

# Run lint on those files
pnpm nx affected:lint --base=HEAD~1

# Run typecheck
pnpm nx affected:typecheck --base=HEAD~1
```

**Common causes**:
1. TypeScript compilation errors (backup-manager has known issues)
2. New lint errors in staged files
3. Python linting errors (if Python files changed)

**Fixes**:

```bash
# Option 1: Fix the errors
pnpm nx lint <project> --fix
git add <fixed-files>
git commit -m "..."

# Option 2: Emergency bypass (use sparingly!)
git commit --no-verify -m "hotfix: critical issue"
# WARNING: CI will still check, so fix before PR
```

### "TypeScript type checking failed on backup-manager"

**Known Issue**: backup-manager has 14 documented TypeScript errors (demo app, Wave 5 work)

**Workaround**:

```bash
# If your changes don't touch backup-manager:
git commit --no-verify -m "feat: your changes"

# CI will pass because it uses nx affected (backup-manager not affected)

# If you ARE modifying backup-manager:
# Fix the TypeScript errors first, or use --no-verify and note in PR
```

**Status**: Documented in `.claude/epics/clean-up-lints/updates/163-final/FINAL-VALIDATION-REPORT.md`

---

## Pre-commit Hook Issues

### "Hook script not found" or "Permission denied"

**Fix**:

```bash
# Re-install hooks
pnpm install

# Make hook executable
chmod +x .husky/pre-commit

# Verify
test -x .husky/pre-commit && echo "OK" || echo "FAILED"
```

### "pnpm not found in PATH"

**Fix**:

```bash
# Install pnpm globally
npm install -g pnpm

# Or use Corepack (Node 16.9+)
corepack enable
corepack prepare pnpm@latest --activate

# Restart terminal/IDE after installation
```

### Hook takes too long

**Optimization**:

```bash
# Hooks only check affected files (fast)
# If still slow, check what's running:
cat .husky/pre-commit

# Temporarily disable (emergency only)
git commit --no-verify -m "..."
```

---

## Performance Issues

### "Lint takes forever"

**Optimization**:

```bash
# Use Nx affected (only changed files)
pnpm nx affected:lint

# Use Nx cache (should be automatic)
pnpm nx lint <project>  # Second run should be cached

# Clear cache if issues
pnpm nx reset
```

### "TypeScript type checking is slow"

**Optimization**:

```bash
# Check only affected
pnpm nx affected:typecheck

# Use project references (if configured)
pnpm nx typecheck <project>

# Ensure tsconfig.tsbuildinfo is in .gitignore (speeds up incremental builds)
```

---

## Getting More Help

### 1. Check Documentation

- **Rule explanations**: [LINT_RULES_RATIONALE.md](./LINT_RULES_RATIONALE.md)
- **Contribution guide**: [CONTRIBUTING.md](../CONTRIBUTING.md)
- **Type safety patterns**: [TYPE_SAFETY.md](./development/TYPE_SAFETY.md)

### 2. Search Existing Issues

```bash
# Search GitHub for similar errors
gh issue list --label lint --search "no-explicit-any"

# Check closed issues for solutions
gh issue list --label lint --state closed
```

### 3. Ask the Team

- **Slack**: #engineering channel
- **Tag**: @lint-initiative-lead in issue/PR
- **Pair**: Request code review for complex lint errors

### 4. Common Resources

- [TypeScript ESLint Playground](https://typescript-eslint.io/play) - Test rules interactively
- [TypeScript Handbook](https://www.typescriptlang.org/docs/handbook/intro.html) - Official TypeScript docs
- [ESLint Rules](https://eslint.org/docs/latest/rules/) - Official ESLint rule docs

---

## Quick Command Reference

```bash
# Lint specific project
pnpm nx lint <project-name>

# Lint with auto-fix
pnpm nx lint <project-name> --fix

# Lint all projects
pnpm nx run-many --target=lint --all

# Lint only affected (since last commit)
pnpm nx affected:lint

# Typecheck specific project
pnpm nx typecheck <project-name>

# Clear Nx cache
pnpm nx reset

# Run pre-commit checks manually
.husky/pre-commit

# Bypass pre-commit (emergency only)
git commit --no-verify -m "..."
```

---

**Still stuck?** Create an issue or ask in #engineering Slack!

---

*Generated as part of Issue #159 - Documentation & Rollout*
*Epic: clean-up-lints (#154)*
