---
name: type-safety-engineer
description: This skill should be used when improving TypeScript type safety by removing `any` types, adding Zod schemas for runtime validation, creating type guards, and strengthening strictness. Use this skill when the user wants to enhance type safety, mentions "fix any types", "add Zod validation", or requests type improvements for better code quality.
---

# Type Safety Engineer

## Overview

Enhance TypeScript type safety by eliminating `any` types, adding Zod schemas for runtime validation, creating type guards, and strengthening compiler strictness.

## When to Use This Skill

Invoke when user wants to:
- Remove `any` types
- Add runtime validation with Zod
- Improve type safety
- Mentioned "type safety" or "Zod schemas"

## Type Safety Workflow

### Step 1: Scan for Issues

```bash
# Find explicit any
grep -r ": any" libs/ --include="*.ts" | grep -v ".spec.ts"

# Find functions without return types
grep -r "^.*function.*{$" libs/ --include="*.ts" | grep -v ": "

# TypeScript strict mode check
npx tsc --noEmit --strict
```

### Step 2: Categorize Issues

**🔴 Critical:**
- `any` in API response handling
- `any` in service methods
- `any` in store state types

**⚠️ Important:**
- Missing return types
- Untyped parameters
- Weak types (`object`, `Function`)

**ℹ️ Moderate:**
- `any` in test files
- Loose array types

### Step 3: Add Zod Schemas for API Responses

```typescript
import { z } from 'zod';

// Define schema
const OrderItemSchema = z.object({
  productId: z.string().uuid(),
  quantity: z.number().int().positive(),
  price: z.number().positive()
});

const OrderResponseSchema = z.object({
  id: z.string().uuid(),
  status: z.enum(['pending', 'confirmed', 'shipped']),
  items: z.array(OrderItemSchema),
  createdAt: z.string().datetime()
});

// Infer TypeScript type
type OrderResponse = z.infer<typeof OrderResponseSchema>;

// Runtime validation
const order = OrderResponseSchema.parse(apiResponse);
```

### Step 4: Replace `any` with Specific Types

**Pattern 1: Unknown + Type Guards**
```typescript
// BEFORE
function processData(data: any) {
  return data.value;
}

// AFTER
function processData(data: unknown): string {
  if (!isValidData(data)) {
    throw new Error('Invalid data');
  }
  return data.value;
}

function isValidData(data: unknown): data is { value: string } {
  return typeof data === 'object' && data !== null && 'value' in data;
}
```

**Pattern 2: Generic Types**
```typescript
// BEFORE
function findById(items: any[], id: string): any {
  return items.find(item => item.id === id);
}

// AFTER
function findById<T extends { id: string }>(items: T[], id: string): T | undefined {
  return items.find(item => item.id === id);
}
```

### Step 5: Add Type Guards for API Data

```typescript
export function isOrderResponse(data: unknown): data is OrderResponse {
  try {
    OrderResponseSchema.parse(data);
    return true;
  } catch {
    return false;
  }
}

// Use in service
getOrder(id: string): Observable<OrderResponse> {
  return this.http.get(`/api/orders/${id}`).pipe(
    map(response => {
      if (!isOrderResponse(response)) {
        throw new Error('Invalid API response');
      }
      return response;
    })
  );
}
```

### Step 6: Validate Changes

```bash
npx tsc --noEmit --strict
npx nx affected:test --skip-nx-cache
npx nx affected:lint
```

### Step 7: Generate Report

```
Type Safety Improvements
========================

Path: [analyzed path]

🔍 Issues Found
---------------
`any` usages: XX → 0
Missing return types: XX → 0
Untyped parameters: XX → 0

✅ Improvements
---------------
- Added Zod schemas: XX
- Created type guards: XX
- Fixed `any` types: XX
- Added return types: XX

📈 Type Safety Score
--------------------
Before: XX%
After: XX% (+XX%)

💡 Recommendations
------------------
1. Enable stricter TypeScript options
2. Add validation to remaining APIs
```

## Common Patterns

**API Response Validation:**
```typescript
const schema = z.object({...});
type Type = z.infer<typeof schema>;

return this.http.get<unknown>(url).pipe(
  map(response => schema.parse(response))
);
```

**Event Handlers:**
```typescript
// BEFORE: onClick(event: any)
// AFTER: onClick(event: MouseEvent)
```

## References

- Use `docs-researcher` for latest Zod documentation
- Zod: https://zod.dev
- TypeScript strict mode: https://www.typescriptlang.org/tsconfig#strict
