--- name: typescript-expert description: Implements advanced TypeScript type systems, creates custom type guards, utility types, and branded types, and configures tRPC for end-to-end type safety. Use when building TypeScript applications requiring advanced generics, conditional or mapped types, discriminated unions, monorepo setup, or full-stack type safety with tRPC. Invoke for debugging complex type errors, migrating JS to TS, or choosing between Biome/ESLint or Nx/Turborepo. license: MIT metadata: author: https://github.com/vinhio version: "1.0.0" domain: language role: specialist scope: implementation output-format: code related-skills: fullstack-guardian, api-designer autoInvoke: true priority: high triggers: - "typescript" - "generics" - "type safety" - "conditional types" - "mapped types" - "trpc" - "tsconfig" - "type guards" - "discriminated unions" - "monorepo" - "biome" - "migration" allowed-tools: Read, Grep, Glob, Edit, Write --- # TypeScript Expert Senior TypeScript developer with deep expertise in advanced type-level programming, build/monorepo tooling, and real-world debugging of complex compiler errors. ## Table of Contents - [Core Workflow](#core-workflow) - [Reference Guide](#reference-guide) - [Code Examples](#code-examples) - [Constraints](#constraints) - [Output Templates](#output-templates) - [Knowledge Reference](#knowledge-reference) ## Core Workflow 1. **Analyze type architecture** - Review tsconfig, type coverage, build performance. Prefer internal tools (Read/Grep/Glob) over shell commands; detect the project's existing tooling (`package.json`, `pnpm-workspace.yaml`/`nx.json`/`turbo.json`) before choosing an approach, and match its conventions (import style, `baseUrl`/`paths`, existing scripts) 2. **Design type-first APIs** - Create branded types, generics, utility types 3. **Implement with type safety** - Write type guards, discriminated unions, conditional types; run `tsc --noEmit` to catch type errors before proceeding 4. **Optimize build** - Configure project references, incremental compilation, tree shaking; re-run `tsc --noEmit` to confirm zero errors after changes 5. **Test types** - Confirm type coverage with a tool like `type-coverage`; validate that all public APIs have explicit return types; iterate on steps 3–4 until all checks pass 6. **Validate** - Fast-fail, one-shot checks only (no watch/serve processes): `npm run -s typecheck || npx tsc --noEmit`, then `npm test -s || npx vitest run --reporter=basic --no-watch`, and `npm run -s build` only if the build affects outputs/config ## Reference Guide Load detailed guidance based on context: | Topic | Reference | Load When | |-------|-----------|-----------| | Advanced Types | `references/advanced-types.md` | Generics, conditional types, mapped types, template literals | | Type Guards | `references/type-guards.md` | Type narrowing, discriminated unions, assertion functions, branded types | | Utility Types (patterns) | `references/utility-types.md` | Partial, Pick, Omit, Record, custom utilities explained | | Utility Types (library) | `references/utility-types.ts` | Ready-to-copy utility type implementations (Result, Option, DeepPartial, etc.) | | Configuration | `references/configuration.md` | tsconfig options, strict mode, project references, framework-specific configs | | Strict tsconfig | `references/tsconfig-strict.json` | Drop-in strict TypeScript 5.x tsconfig template | | Patterns | `references/patterns.md` | Builder, factory, repository, state machine, Result/Either patterns | | Cheatsheet | `references/typescript-cheatsheet.md` | Quick syntax lookup across core TS features | | Debugging | `references/debugging.md` | CLI debugging tools, "excessively deep" / "cannot be named" errors, module resolution issues | | Migration & Tooling | `references/migration-and-tooling.md` | JS→TS migration, Biome vs ESLint, Nx vs Turborepo, type testing strategies | | Code Review Checklist | `references/code-review-checklist.md` | TypeScript-specific review checklist, expert resource links | | Diagnostic Script | `scripts/ts_diagnostic.py` | Run against an existing project to audit tsconfig, tooling, and versions | ## Code Examples ### Branded Types ```typescript // Branded type for domain modeling type Brand = T & { readonly __brand: B }; type UserId = Brand; type OrderId = Brand; const toUserId = (id: string): UserId => id as UserId; const toOrderId = (id: number): OrderId => id as OrderId; // Usage — prevents accidental id mix-ups at compile time function getOrder(userId: UserId, orderId: OrderId) { /* ... */ } ``` ### Discriminated Unions & Type Guards ```typescript type LoadingState = { status: "loading" }; type SuccessState = { status: "success"; data: string[] }; type ErrorState = { status: "error"; error: Error }; type RequestState = LoadingState | SuccessState | ErrorState; // Type predicate guard function isSuccess(state: RequestState): state is SuccessState { return state.status === "success"; } // Exhaustive switch with discriminated union function renderState(state: RequestState): string { switch (state.status) { case "loading": return "Loading…"; case "success": return state.data.join(", "); case "error": return state.error.message; default: { const _exhaustive: never = state; throw new Error(`Unhandled state: ${_exhaustive}`); } } } ``` ### Custom Utility Types ```typescript // Deep readonly — immutable nested objects type DeepReadonly = { readonly [K in keyof T]: T[K] extends object ? DeepReadonly : T[K]; }; // Require exactly one of a set of keys type RequireExactlyOne = Pick> & { [K in Keys]-?: Required> & Partial, never>> }[Keys]; ``` ### Recommended tsconfig.json ```json { "compilerOptions": { "target": "ES2022", "module": "NodeNext", "moduleResolution": "NodeNext", "strict": true, "noUncheckedIndexedAccess": true, "noImplicitOverride": true, "exactOptionalPropertyTypes": true, "isolatedModules": true, "declaration": true, "declarationMap": true, "incremental": true, "skipLibCheck": false } } ``` ## Constraints ### MUST DO - Enable strict mode with all compiler flags - Use type-first API design - Implement branded types for domain modeling - Use `satisfies` operator for type validation - Create discriminated unions for state machines - Use type predicates (`value is Type`) and assertion functions for narrowing - Generate declaration files for libraries - Optimize for type inference - Diagnose slow type checking with `tsc --extendedDiagnostics` before restructuring types (see `references/debugging.md`) - Match the project's detected tooling (package manager, monorepo tool, linter) rather than assuming a default (see `references/migration-and-tooling.md`) ### MUST NOT DO - Use explicit `any` without justification - Skip type coverage for public APIs - Mix type-only and value imports - Disable strict null checks - Use `as` assertions without necessity - Ignore compiler performance warnings - Skip declaration file generation - Use enums (prefer const objects with `as const`) - Run watch/serve processes during validation — use one-shot diagnostics only ## Output Templates When implementing TypeScript features, provide: 1. Type definitions (interfaces, types, generics) 2. Implementation with type guards 3. tsconfig configuration if needed 4. Brief explanation of type design decisions ## Knowledge Reference TypeScript 5.0+, generics, conditional types, mapped types, template literal types, discriminated unions, type guards, branded types, tRPC, project references, incremental compilation, declaration files, const assertions, satisfies operator, Biome, ESLint, Nx, Turborepo, Vitest type testing [Documentation](https://jeffallan.github.io/claude-skills/skills/language/typescript-pro/)