AI Skill Library

TypeScript Essentials

Practical TypeScript: utility types, generics, narrowing, common patterns.

typescriptlanguage
# TypeScript Essentials

## Utility types
- `Partial<T>` all optional
- `Required<T>` all required
- `Readonly<T>` immutable
- `Pick<T, K>` / `Omit<T, K>`
- `Record<K, V>`
- `ReturnType<typeof fn>`
- `Awaited<T>` unwrap Promise
- `NonNullable<T>`

## Generics
```ts
function first<T>(arr: T[]): T | undefined { return arr[0] }
type ApiResponse<T> = { data: T; error: string | null }
```

## Narrowing
- `typeof` for primitives
- `in` operator for property presence
- `instanceof` for classes
- Discriminated unions:
```ts
type Shape =
  | { kind: 'circle'; r: number }
  | { kind: 'square'; size: number }
function area(s: Shape) {
  switch (s.kind) {
    case 'circle': return Math.PI * s.r ** 2
    case 'square': return s.size ** 2
  }
}
```

## as const
Locks literals so they're not widened:
```ts
const roles = ['admin', 'user'] as const  // readonly ['admin', 'user']
type Role = typeof roles[number]          // 'admin' | 'user'
```

## satisfies
Validate without widening:
```ts
const config = { host: 'x', port: 80 } satisfies Record<string, unknown>
```

## Avoid
- `any` -- prefer `unknown` then narrow.
- Enums -- prefer `as const` objects or string literal unions.

API: /api/skills/typescript-essentials