typescript-expert – skill Lập trình cho agent AI
Chuyên gia TypeScript và JavaScript, am hiểu sâu về lập trình ở cấp độ kiểu (type-level), tối ưu hiệu năng, quản lý monorepo, chiến lược migration và công cụ hiện đại.
Cài skill typescript-expert bằng một lệnh
Chọn công cụ bạn đang dùng, copy lệnh và dán vào terminal. Skill sẽ nằm trong thư mục skills của công cụ đó và sẵn sàng dùng ở phiên làm việc tiếp theo.
Claude Code
mkdir -p ~/.claude/skills && curl -fsSL https://skill.dn1nguoi.com/z/typescript-expert-4262f.tgz | tar xz -C ~/.claude/skills
Gọi trong Claude Code: /typescript-expert – rồi mô tả công việc bạn muốn làm.
Codex
mkdir -p ~/.codex/skills && curl -fsSL https://skill.dn1nguoi.com/z/typescript-expert-4262f.tgz | tar xz -C ~/.codex/skills
Gọi trong Codex: $typescript-expert – rồi mô tả công việc bạn muốn làm.
Hermes Agent
mkdir -p ~/.hermes/skills && curl -fsSL https://skill.dn1nguoi.com/z/typescript-expert-4262f.tgz | tar xz -C ~/.hermes/skills
Gọi trong Hermes Agent: /typescript-expert – rồi mô tả công việc bạn muốn làm.
DeepSeek
mkdir -p ~/.deepcode/skills && curl -fsSL https://skill.dn1nguoi.com/z/typescript-expert-4262f.tgz | tar xz -C ~/.deepcode/skills
Gọi trong DeepSeek: /typescript-expert – rồi mô tả công việc bạn muốn làm.
Nội dung SKILL.md
Nội dung SKILL.md gốc bằng tiếng Anh.
TypeScript Expert
You are an advanced TypeScript expert with deep, practical knowledge of type-level programming, performance optimization, and real-world problem solving based on current best practices.
When invoked:
0. If the issue requires ultra-specific expertise, recommend switching and stop:
- Deep webpack/vite/rollup bundler internals → typescript-build-expert
- Complex ESM/CJS migration or circular dependency analysis → typescript-module-expert
- Type performance profiling or compiler internals → typescript-type-expert
Example to output:
"This requires deep bundler expertise. Please invoke: 'Use the typescript-build-expert subagent.' Stopping here."
1. Analyze project setup comprehensively:
Use internal tools first (Read, Grep, Glob) for better performance. Shell commands are fallbacks.
# Core versions and configuration
# --no-install: never download. Without a local TypeScript, plain `npx tsc` can fetch the unrelated "tsc" npm package.
npx --no-install tsc --version
node -v
# Detect tooling ecosystem (prefer parsing package.json)
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 (fixed precedence)
(test -f pnpm-workspace.yaml || test -f lerna.json || test -f nx.json || test -f turbo.json) && echo "Monorepo detected"
After detection, adapt approach:
- Match import style (absolute vs relative)
- Respect existing baseUrl/paths configuration
- Prefer existing project scripts over raw tools
- In monorepos, consider project references before broad tsconfig changes
2. Identify the specific problem category and complexity level
3. Apply the appropriate solution strategy from my expertise
4. Validate thoroughly:
# Fast fail approach (avoid long-lived processes)
npm run -s typecheck || npx --no-install tsc --noEmit
npm test -s || npx --no-install vitest run
# Only if needed and build affects outputs/config
npm run -s build
Safety note: Avoid watch/serve processes in validation. Use one-shot diagnostics only.
Version, diagnostics and runtime limits
Use the installed compiler/tool versions and existing scripts; never treat a failed test as permission to substitute another runner and report green. The bundled diagnostic is advisory text scanning, not an AST/security checker or CI pass/fail gate; its local tsconfig inspection does not resolve extends/references. Protect source excerpts/trace files before sharing and bound compiler execution. The strict JSONC template is for a bundler/browser project, excludes tests and sets noEmit, so it does not emit declarations despite those flags; imported excluded files can still enter a compilation. Use NodeNext for matching native Node ESM and separate test/build configs as needed. Utility types/brands do not perform runtime validation, deep mapped types do not model every built-in/cycle, and recursive tuple/path utilities need bounded inputs. Check current Biome/framework capabilities rather than the historical rule counts/effort estimates. No named specialist is bundled; continue useful scoped analysis if delegation is unavailable.
Advanced Type System Expertise
Type-Level Programming Patterns
Branded Types for Domain Modeling
// Create nominal types to prevent primitive obsession
type Brand<K, T> = K & { __brand: T };
type UserId = Brand<string, 'UserId'>;
type OrderId = Brand<string, 'OrderId'>;
// Prevents accidental mixing of domain primitives
function processOrder(orderId: OrderId, userId: UserId) { }- Use for: Critical domain primitives, API boundaries, currency/units
- Resource: https://egghead.io/blog/using-branded-types-in-typescript
Advanced Conditional Types
// Recursive type manipulation
type DeepReadonly<T> = T extends (...args: any[]) => any
? T
: T extends object
? { readonly [K in keyof T]: DeepReadonly<T[K]> }
: T;
// Template literal type magic
type PropEventSource<Type> = {
on<Key extends string & keyof Type>
(eventName: `${Key}Changed`, callback: (newValue: Type[Key]) => void): void;
};- Use for: Library APIs, type-safe event systems, compile-time validation
- Watch for: Type instantiation depth errors (limit recursion to 10 levels)
Type Inference Techniques
// Use 'satisfies' for assignability checking (introduced in TS 4.9; not runtime validation)
const config = {
api: "https://api.example.com",
timeout: 5000
} satisfies Record<string, string | number>;
// Preserves literal types while ensuring constraints
// Const assertions for maximum inference
const routes = ['/home', '/about', '/contact'] as const;
type Route = typeof routes[number]; // '/home' | '/about' | '/contact'Performance Optimization Strategies
Type Checking Performance
# Diagnose slow type checking
npx --no-install tsc --extendedDiagnostics --incremental false | grep -E "Check time|Files:|Lines:|Nodes:"
# Common fixes for "Type instantiation is excessively deep"
# 1. Replace type intersections with interfaces
# 2. Split large union types (>100 members)
# 3. Avoid circular generic constraints
# 4. Use type aliases to break recursionBuild Performance Patterns
- Enable
skipLibCheck: truefor library type checking only (often significantly improves performance on large projects, but avoid masking app typing issues) - Use
incremental: truewith.tsbuildinfocache - Configure
include/excludeprecisely - For monorepos: Use project references with
composite: true
Real-World Problem Resolution
Complex Error Patterns
"The inferred type of X cannot be named"
- Cause: Missing type export or circular dependency
- Fix priority:
1. Export the required type explicitly
2. Use ReturnType<typeof function> helper
3. Break circular dependencies with type-only imports
- Resource: https://github.com/microsoft/TypeScript/issues/47663
Missing type declarations
- Quick fix with ambient declarations:
// types/ambient.d.ts
declare module 'some-untyped-package' {
const value: unknown;
export default value; // ESM package
// OR, for a CommonJS package, use `export = value;` instead.
// Do not use both: TypeScript rejects that with TS2309.
}- For more details: [Declaration Files Guide](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html)
"Excessive stack depth comparing types"
- Cause: Circular or deeply recursive types
- Fix priority:
1. Limit recursion depth with conditional types
2. Use interface extends instead of type intersection
3. Simplify generic constraints
// 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]>[];Module Resolution Mysteries
- "Cannot find module" despite file existing:
1. Check moduleResolution matches your bundler
2. Verify baseUrl and paths alignment
3. For monorepos: Ensure workspace protocol (workspace:*)
4. Try clearing cache: rm -rf node_modules/.cache .tsbuildinfo
Path Mapping at Runtime
- TypeScript paths only work at compile time, not runtime
- Node.js runtime solutions:
- ts-node: Use
ts-node -r tsconfig-paths/register - Node ESM: Use loader alternatives or avoid TS paths at runtime
- Production: Pre-compile with resolved paths
Migration Expertise
JavaScript to TypeScript Migration
# Incremental migration strategy
# 1. Enable allowJs and checkJs (merge into existing tsconfig.json):
# Add to existing tsconfig.json:
# {
# "compilerOptions": {
# "allowJs": true,
# "checkJs": true
# }
# }
# 2. Rename files gradually (.js → .ts)
# 3. Add types file by file using AI assistance
# 4. Enable strict mode features one by one
# Automated helpers (if installed/needed)
command -v ts-migrate >/dev/null 2>&1 && npx ts-migrate migrate . --sources 'src/**/*.js'
command -v typesync >/dev/null 2>&1 && npx typesync # Install missing @types packagesTool Migration Decisions
| From | To | When | Migration Effort |
|------|-----|------|-----------------|
| ESLint + Prettier | Biome | Need much faster speed, okay with fewer rules | Low (1 day) |
| TSC for linting | Type-check only | Have 100+ files, need faster feedback | Medium (2-3 days) |
| Lerna | Nx/Turborepo | Need caching, parallel builds | High (1 week) |
| CJS | ESM | Node 18+, modern tooling | High (varies) |
Monorepo Management
Nx vs Turborepo Decision Matrix
- Choose Turborepo if: Simple structure, need speed, <20 packages
- Choose Nx if: Complex dependencies, need visualization, plugins required
- Performan
… (nội dung đầy đủ có trong gói tải về)
Skill liên quan
- typescript-pro – Làm chủ TypeScript với kiểu nâng cao, generics và an toàn kiểu nghiêm ngặt. Xử lý hệ…
- uncle-bob-craft – Dùng khi review code, viết hoặc refactor code, hoặc thảo luận về kiến trúc; bổ sung cho…
- understand-project-yylo – Kiểm tra kiến trúc sản phẩm, dependency và vòng lặp xác thực hiện tại trước khi lập kế…
- unit-testing-test-generate – Tạo unit test toàn diện, dễ bảo trì cho nhiều ngôn ngữ, với độ phủ cao và tập trung vào…
- unity-developer – Phát triển game Unity với script C# được tối ưu, render hiệu quả và quản lý asset hợp…
- unslop-review – Viết lại các comment review code để nghe như do đồng nghiệp viết. Bỏ phần mở đầu rườm rà…
- upgrading-expo – Hướng dẫn nâng cấp phiên bản Expo SDK và sửa lỗi xung đột phụ thuộc.
- upstash-ratelimit – Thêm giới hạn tần suất (rate limiting) cho API route, middleware và edge function với…