> ## Documentation Index
> Fetch the complete documentation index at: https://docs.encoreos.io/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript Type Generation Guide

> Version: 2.0.0 Last Updated: 2026-01-15 Purpose: Generate TypeScript types from Supabase database schema after migration.

**Version:** 2.0.0\
**Last Updated:** 2026-01-15\
**Purpose:** Generate TypeScript types from Supabase database schema after migration.

***

## Overview

TypeScript types provide type safety for database operations. This guide covers generating types using both CLI (recommended) and MCP approaches.

**Recommendation:** Use CLI for type generation as it provides better error handling and integrates with build scripts.

***

## Prerequisites

**Verify Setup:**

**MCP Check:**

```typescript theme={null}
// Verify project URL
mcp_supabase_get_project_url()

// List tables to confirm migrations applied
mcp_supabase_list_tables({ schemas: ["public"] })
// Expected: ~465 tables
```

**CLI Check:**

```bash theme={null}
# Verify CLI installed
supabase --version

# Verify project linked
supabase status
```

***

## Method 1: Generate via CLI (Recommended)

### Step 1: Set Project ID

**Option A: Environment Variable**

```bash theme={null}
export SUPABASE_PROJECT_ID=<your-project-ref>
```

**Option B: .env.local File**

```bash theme={null}
echo "SUPABASE_PROJECT_ID=<your-project-ref>" >> .env.local
```

**Note:** Get project ID from `mcp_supabase_get_project_url()` or Supabase dashboard.

### Step 2: Generate Types

**Using Script:**

```bash theme={null}
# Make script executable (if needed)
chmod +x scripts/generate-types.sh

# Run type generation
./scripts/generate-types.sh
```

**Or Manual Command:**

```bash theme={null}
supabase gen types typescript --project-id <your-project-ref> > src/integrations/supabase/types.ts
```

### Step 3: Validate Generated Types

**CLI:**

```bash theme={null}
# Run TypeScript type check
npm run typecheck
# Expected: 0 errors

# Check file size (should be substantial)
(Get-Item "src/integrations/supabase/types.ts").Length
# Expected: > 100KB for 465 tables
```

**Verify Content:**

```bash theme={null}
# Count table definitions (PowerShell)
(Select-String -Path "src/integrations/supabase/types.ts" -Pattern "Row:" -AllMatches).Matches.Count
# Expected: ~465

# Or (bash)
grep -c "Row:" src/integrations/supabase/types.ts
# Expected: ~465
```

***

## Method 2: Generate via MCP (Alternative)

### Step 1: Generate Types

```typescript theme={null}
mcp_supabase_generate_typescript_types()
```

### Step 2: Verify Output

The MCP will return generated types. You'll need to save them to the types file manually.

**Note:** CLI is preferred because:

* Better error messages
* Automatic file output
* Integrates with scripts
* More reliable for large schemas

***

## Validation Checklist

After generating types, verify:

* [ ] File size is substantial (>100KB for 465 tables)
* [ ] `npm run typecheck` passes with 0 errors
* [ ] No empty type definitions (`[_ in never]: never`)
* [ ] All modules have type definitions:

**Verify Module Types (MCP):**

```typescript theme={null}
// Cross-reference with table list
mcp_supabase_list_tables({ schemas: ["public"] })
```

**Expected Type Definitions:**

| Module                       | Expected Tables | Types Present |
| ---------------------------- | --------------- | ------------- |
| Platform Foundation (pf\_)   | \~74            | \[ ]          |
| Human Resources (hr\_)       | \~94            | \[ ]          |
| Finance & Accounting (fa\_)  | \~46            | \[ ]          |
| Forms & Workflow (fw\_)      | \~54            | \[ ]          |
| Recovery Housing (rh\_)      | \~51            | \[ ]          |
| Governance & Risk (gr\_)     | \~49            | \[ ]          |
| Facilities Management (fm\_) | \~22            | \[ ]          |
| Leadership OS (lo\_)         | \~29            | \[ ]          |
| IT Service Management (it\_) | \~35            | \[ ]          |

***

## Troubleshooting

### Issue: Types file is empty or minimal

**Symptoms:** `types.ts` only contains empty type definitions or is very small

**Verify Database Has Tables (MCP):**

```typescript theme={null}
mcp_supabase_execute_sql({
  query: `SELECT COUNT(*) as table_count FROM information_schema.tables WHERE table_schema = 'public';`
})
// Expected: ~465
```

**Solutions:**

1. Verify project ID is correct
2. Check Supabase CLI authentication: `supabase login`
3. Try linking project: `supabase link --project-ref <project-ref>`
4. Verify migrations are applied: `mcp_supabase_list_migrations()`

### Issue: Type errors after generation

**Symptoms:** `npm run typecheck` shows errors

**Check Database Schema (MCP):**

```typescript theme={null}
// Check specific table schema
mcp_supabase_execute_sql({
  query: `
    SELECT column_name, data_type, is_nullable
    FROM information_schema.columns
    WHERE table_name = '<table_name>'
    ORDER BY ordinal_position;
  `
})
```

**Solutions:**

1. Review error messages - may indicate schema changes needed
2. Check for breaking changes in Supabase client library
3. Update code to match new types
4. If types are incorrect, restore backup and regenerate

### Issue: Missing tables in types

**Symptoms:** Some tables don't appear in generated types

**Verify Tables Exist (MCP):**

```typescript theme={null}
mcp_supabase_execute_sql({
  query: `SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_name LIKE '<prefix>%';`
})
```

**Solutions:**

1. Verify tables exist in database
2. Check table is in `public` schema (default for type generation)
3. Regenerate types after ensuring all migrations are applied

### Issue: CLI command fails

**Symptoms:** `supabase gen types typescript` returns error

**Check Connection:**

```bash theme={null}
# Verify logged in
supabase projects list

# Verify linked
supabase status
```

**Solutions:**

1. Re-authenticate: `supabase login`
2. Re-link project: `supabase link --project-ref <project-ref>`
3. Check network connectivity
4. Try MCP as fallback

***

## When to Regenerate Types

* After applying new migrations
* After schema changes in staging/production
* Before major releases
* When type errors appear in codebase
* After migration validation completes

***

## Backup Strategy

The generate script automatically backs up existing types before generating new ones:

* **Backup location:** `src/integrations/supabase/types.ts.backup.YYYYMMDD_HHMMSS`
* **Restore:** `mv src/integrations/supabase/types.ts.backup.* src/integrations/supabase/types.ts`

***

## Integration with CI/CD

For automated type generation in CI:

```yaml theme={null}
# .github/workflows/generate-types.yml
- name: Generate TypeScript types
  run: |
    export SUPABASE_PROJECT_ID=${{ secrets.SUPABASE_PROJECT_ID }}
    ./scripts/generate-types.sh
  env:
    SUPABASE_ACCESS_TOKEN: ${{ secrets.SUPABASE_ACCESS_TOKEN }}
```

***

## Quick Reference

| Task                 | Tool | Command                                           |
| -------------------- | ---- | ------------------------------------------------- |
| Generate types       | CLI  | `supabase gen types typescript --project-id <id>` |
| Generate types       | MCP  | `mcp_supabase_generate_typescript_types()`        |
| Verify table count   | MCP  | `mcp_supabase_list_tables()`                      |
| Check specific table | MCP  | `mcp_supabase_execute_sql()`                      |
| Type check           | CLI  | `npm run typecheck`                               |

***

## Related Documentation

* [Completion Plan](COMPLETION_PLAN.md) - Full migration workflow
* [MCP Usage Guide](../development/MCP_USAGE.md) - When to use MCP vs CLI
* [Pre-Production Checklist](PRE_PRODUCTION_CHECKLIST.md) - Final validation

***

**Last Updated:** 2026-01-15\
**Version:** 2.0.0
