typescript
TypeScript Expert
Collaborating skills
- Vitest: skill:
vitestfor testing TypeScript code with Vitest framework - Refactor: skill:
refactorfor improving TypeScript code with test coverage - TDD: skill:
tddfor test-driven development workflow in TypeScript
Expert guidance for TypeScript development. This skill uses progressive disclosure - read sections as needed, and dive into reference files when you need deeper coverage.
Quick Start
Analyze the project setup first:
# Core versions
npx tsc --version && node -v
# Check for tooling ecosystem
node -e "const p=require('./package.json');console.log(Object.keys({...p.devDependencies,...p.dependencies}||{}).join('\n'))" 2>/dev/null | grep -E 'biome|eslint|prettier|vitest|jest|turborepo|nx' || echo "No tooling detected"
# Check for monorepo
(test -f pnpm-workspace.yaml || test -f lerna.json || test -f nx.json || test -f turbo.json) && echo "Monorepo detected"
After detection, adapt your approach:
- Match import style (absolute vs relative)
- Respect existing baseUrl/paths configuration
- Prefer existing project scripts over raw tools
Common Issues
Type Errors
"The inferred type of X cannot be named"
Cause: Missing type export or circular dependency Fix priority:
- Export the required type explicitly
- Use
ReturnType<typeof function>helper - Break circular dependencies with type-only imports
export type { MyType };
export type MyReturnType = ReturnType<typeof myFunction>;
"Excessive stack depth comparing types"
Cause: Circular or deeply recursive types
// Bad: Infinite recursion
type InfiniteArray<T> = T | InfiniteArray<T>[];
// Good: Limited recursion
type NestedArray<T, D extends number = 5> =
D extends 0 ? T : T | NestedArray<T, [-1, 0, 1, 2, 3, 4][D]>[];
Missing type declarations
Read
references/declaration-files.mdfor comprehensive guidance on writing .d.ts files.
// types/ambient.d.ts
declare module 'some-untyped-package' {
const value: unknown;
export default value;
}
Module Resolution
"Cannot find module" despite file existing:
- Check
moduleResolutionmatches your bundler - Verify
baseUrlandpathsalignment - For monorepos: Ensure workspace protocol (workspace:*)
- Clear cache:
rm -rf node_modules/.cache .tsbuildinfo
Type Patterns
Branded Types
Prevent primitive obsession by creating nominal types:
declare const __brand: unique symbol;
type Brand<B> = { [__brand]: B };
export type Branded<T, B> = T & Brand<B>;
type UserId = Branded<string, 'UserId'>;
type OrderId = Branded<string, 'OrderId'>;
function processOrder(orderId: OrderId, userId: UserId) { }
// processOrder(userId, orderId) // Error: Type mismatch
Read
references/type-patterns.mdwhen you need: conditional types, template literal types, mapped types, type inference techniques, or advanced utility patterns.
Const Assertions & Satisfies
// Const assertions for literal types
const routes = ['/home', '/about', '/contact'] as const;
type Route = typeof routes[number]; // '/home' | '/about' | '/contact'
// satisfies for constraint validation (TS 5.0+)
const config = {
api: "https://api.example.com",
timeout: 5000
} satisfies Record<string, string | number>;
Performance
Diagnosing Slow Type Checking
# Get diagnostics
npx tsc --extendedDiagnostics --incremental false | grep -E "Check time|Files:|Lines:|Nodes:"
# Generate trace for deep analysis
npx tsc --generateTrace trace --incremental false
npx @typescript/analyze-trace trace
Quick Fixes
- Enable
skipLibCheck: true(often significant improvement) - Use
incremental: truewith.tsbuildinfocache - Configure
include/excludeprecisely - For monorepos: Use project references with
composite: true
Read
references/performance.mdwhen: type checking is slow, you see "Type instantiation too deep" errors, or you need monorepo performance optimization.
Tooling
Biome vs ESLint
| Use Biome | Use ESLint |
|---|---|
| Speed is critical | Need specific rules/plugins |
| Single tool for lint + format | Complex custom rules |
| TypeScript-first | Vue/Angular projects |
| Fewer rules OK | Type-aware linting needed |
Read
references/tooling.mdwhen: setting up linting/formatting, choosing between Biome/ESLint/Prettier, configuring monorepo tools (Nx vs Turborepo), or migrating between tools.
Type Testing
// avatar.test-d.ts
import { expectTypeOf } from 'vitest'
import type { Avatar } from './avatar'
test('Avatar props are correctly typed', () => {
expectTypeOf<Avatar>().toHaveProperty('size')
expectTypeOf<Avatar['size']>().toEqualTypeOf<'sm' | 'md' | 'lg'>()
})
Run with: vitest --typecheck
Read
references/type-testing.mdwhen: testing library types, using expectTypeOf/assertType APIs, or setting up type test infrastructure.
Configuration
Strict Settings (Recommended)
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"exactOptionalPropertyTypes": true,
"noPropertyAccessFromIndexSignature": true
}
}
ESM-First Approach
- Set
"type": "module"in package.json - Use
.mtsfor TypeScript ESM files if needed - Configure
"moduleResolution": "bundler"for modern tools - Dynamic imports for CJS:
const pkg = await import('cjs-package')
Migration
JavaScript to TypeScript
# 1. Enable allowJs in tsconfig.json
# 2. Rename files gradually (.js → .ts)
# 3. Add types file by file
# 4. Enable strict mode features one by one
# Helpers
npx ts-migrate migrate . --sources 'src/**/*.js'
npx typesync # Install missing @types packages
Tool Migration Guide
| From | To | When | Effort |
|---|---|---|---|
| ESLint + Prettier | Biome | Need speed | Low (1 day) |
| Lerna | Nx/Turborepo | Caching needed | High (1 week) |
| CJS | ESM | Node 18+ | High (varies) |
Monorepo
Nx vs Turborepo:
- Turborepo: Simple structure, need speed, <20 packages
- Nx: Complex dependencies, need visualization, plugins required
// Root tsconfig.json
{
"references": [
{ "path": "./packages/core" },
{ "path": "./packages/ui" }
],
"compilerOptions": {
"composite": true,
"declaration": true,
"declarationMap": true
}
}
See
references/performance.mdfor monorepo performance optimization.
Validation
After changes, validate thoroughly:
npm run -s typecheck || npx tsc --noEmit
npm test -s || npx vitest run --reporter=basic --no-watch
npm run -s build # Only if build affects outputs
Deep Dive: Reference Files
Load these files when you need comprehensive coverage:
| File | Read When |
|---|---|
references/type-patterns.md |
Building complex types, conditional types, template literals, branded types, inference techniques |
references/performance.md |
Slow type checking, "excessive depth" errors, monorepo optimization, compiler diagnostics |
references/type-testing.md |
Testing library types, expectTypeOf/assertType APIs, Vitest typecheck setup |
references/declaration-files.md |
Writing .d.ts files, module augmentation, ambient declarations, publishing types |
references/tooling.md |
Biome/ESLint setup, Nx/Turborepo comparison, migration guides, development tools |
Each reference file includes table of contents, code examples, and troubleshooting guides.
More from mguinada/agent-skills
create-pr
Creates GitHub pull requests with properly formatted titles, a body matching the project's PR template, and appropriate type/scope labels. Automatically creates labels if they don't exist. Use when creating PRs, submitting changes for review, or when the user says /pr or asks to create a pull request. **PROACTIVE ACTIVATION**: Auto-invoke when a branch has commits ahead of main and the user signals the work is ready. **DETECTION**: Run git log origin/main..HEAD - if commits exist and user signals readiness, offer to open a PR. User says \"open a PR\", \"ready for review\", \"this is done\", \"let's merge\", \"submit this\". **USE CASES**: Feature or fix complete, user finished a series of commits and mentions review or merging.
11copilot-sdk
Build agentic applications with GitHub Copilot SDK. Use when embedding AI agents in apps, creating custom tools, implementing streaming responses, managing sessions, connecting to MCP servers, or creating custom agents. Triggers on Copilot SDK, GitHub SDK, agentic app, embed Copilot, programmable agent, MCP server, custom agent. **PROACTIVE ACTIVATION**: Auto-invoke when building agentic applications or integrating Copilot SDK. **DETECTION**: Check for @github/copilot-sdk imports, copilot dependencies in package.json/pyproject.toml/go.mod. **USE CASES**: Embedding agents in apps, creating custom tools, implementing streaming, managing sessions, connecting to MCP servers.
9agents-md-creator
|
9rails
Ruby on Rails framework development covering MVC architecture, Active Record, migrations, routing, background jobs, and full-stack web applications. **PROACTIVE ACTIVATION**: Auto-invoke when editing Ruby files in a Rails project, running rails commands, or working with Rails-specific patterns. **DETECTION**: Check for Gemfile with 'rails' gem, config/application.rb, app/ directory (controllers, models, views), db/migrate/, config/routes.rb, bin/rails, or *.rb files with ActionController/ActiveRecord imports. **USE CASES**: Creating controllers/models/migrations, building REST APIs, background jobs with Active Job, real-time features with Action Cable, file uploads with Active Storage, email with Action Mailer, internationalization, authentication, and Rails configuration.
1changelog
Generate and maintain a structured CHANGELOG.md following Keep a Changelog format and Semantic Versioning. Use when preparing a release, documenting version changes, writing release notes, or updating changelogs. **PROACTIVE ACTIVATION**: Invoke when user says 'update changelog', 'write release notes', 'bump version', 'prepare release', '/changelog', or after a `create-pr` is merged. **USE CASES**: Pre-release changelog updates, generating notes from git history since last tag, writing user-friendly release notes, documenting breaking changes with migration guides.
1design-pattern-adopter
|
1