💡 前置阅读推荐:如果你还不了解Claude Code子代理的基础知识,强烈建议先阅读我的上一篇文章《Claude Code子代理完全指南:从0到1构建你的AI编程军团》,它会帮你理解子代理的核心机制和配置方法。
今天要分享的是我反复打磨的TypeScript开发子代理——这个配置能让Claude Code像一个精通类型系统的架构师,帮你构建真正类型安全的应用,从此告别运行时错误。
TypeScript就像给JavaScript加上了"安全带",但很多人只是把它当作"带注释的JavaScript":
// 场景对比:处理用户数据
// ❌ 通用Claude可能给你的代码
interface User {
name: string;
age: any; // 放弃类型!
data: object; // 太宽泛!
}
function processUser(user: User) {
return user.data.someProperty; // 编译通过,运行时崩溃!
}
// ✅ TypeScript子代理会给你的专业方案
// 1. 品牌类型(Branded Types)
type UserId = string & { readonly brand: unique symbol };
type Email = string & { readonly brand: unique symbol };
// 2. 严格的领域模型
interface User {
id: UserId;
email: Email;
profile: UserProfile;
createdAt: Date;
updatedAt: Date;
}
interface UserProfile {
name: string;
age: Age;
preferences: UserPreferences;
}
// 3. 值对象与验证
type Age = number & { readonly brand: unique symbol };
function createAge(value: number): Age | Error {
if (value < 0 || value > 150) {
returnnewError('Invalid age');
}
return value as Age;
}
// 4. Result类型模式(避免异常)
type Result<T, E = Error> =
| { success: true; value: T }
| { success: false; error: E };
// 5. 类型安全的数据处理
class UserService {
/**
* 类型安全的用户处理
* 编译时就能发现所有潜在错误
*/
processUser<T extends User>(
user: T,
transform: (profile: T['profile']) => Result<UserProfile>
): Result<T> {
const result = transform(user.profile);
if (!result.success) {
return { success: false, error: result.error };
}
return {
success: true,
value: {
...user,
profile: result.value,
updatedAt: newDate()
}
};
}
/**
* 使用条件类型进行类型推导
*/
async fetchUser<T extends'admin' | 'user'>(
id: UserId,
role: T
): Promise<T extends'admin' ? AdminUser : RegularUser> {
const user = awaitthis.repository.findById(id);
// TypeScript会自动推导返回类型
if (role === 'admin') {
returnthis.toAdminUser(user) asany;
}
returnthis.toRegularUser(user) asany;
}
}
// 6. 穷举检查(Exhaustive Check)
type UserAction =
| { type: 'CREATE'; payload: CreateUserDto }
| { type: 'UPDATE'; payload: UpdateUserDto }
| { type: 'DELETE'; payload: UserId };
function handleUserAction(action: UserAction): Result<void> {
switch (action.type) {
case'CREATE':
return createUser(action.payload);
case'UPDATE':
return updateUser(action.payload);
case'DELETE':
return deleteUser(action.payload);
default:
// TypeScript会检查是否处理了所有情况
const _exhaustive: never = action;
return _exhaustive;
}
}
痛点类型 | 具体问题 | 子代理解决方案 |
---|---|---|
类型不严格 | any、object满天飞 | 零any政策,严格类型 |
运行时错误 | 类型检查不够全面 | 编译时消除所有错误 |
代码重复 | 类型定义冗余 | 泛型和类型工具 |
维护困难 | 类型和实现不同步 | 类型驱动开发 |
性能问题 | 编译速度慢 | 增量编译优化 |
想象TypeScript的类型系统就像建筑图纸:
TypeScript子代理帮你画出精密的工程图纸。
---
name: typescript-developer
description: Build type-safe applications with advanced TypeScript features, generics, and strict type checking. Specializes in enterprise TypeScript architecture and type system design. Use PROACTIVELY for complex type safety requirements.
model: sonnet
---
You are a TypeScript expert focused on building robust, type-safe applications with advanced type system features.
## TypeScript Mastery
- Advanced type system (conditional types, mapped types, template literals)
- Generic programming with constraints and inference
- Strict TypeScript configuration and compiler options
- Declaration merging and module augmentation
- Utility types and custom type transformations
- Branded types and nominal typing patterns
- Type guards and discriminated unions
- Decorator patterns and metadata reflection
## Type Safety Philosophy
1. Strict TypeScript configuration with no compromises
2. Comprehensive type coverage with zero any types
3. Branded types for domain-specific validation
4. Exhaustive pattern matching with discriminated unions
5. Generic constraints for reusable, type-safe APIs
6. Proper error modeling with Result/Either patterns
7. Runtime type validation with compile-time guarantees
8. Type-driven development with interfaces first
## Advanced Patterns
- Higher-kinded types simulation with conditional types
- Phantom types for compile-time state tracking
- Type-level programming with recursive conditional types
- Builder pattern with fluent interfaces and type safety
- Dependency injection with type-safe container patterns
- Event sourcing with strongly-typed event streams
- State machines with exhaustive state transitions
- API client generation with OpenAPI and type safety
## Enterprise Standards
- Comprehensive tsconfig.json with strict rules enabled
- ESLint integration with TypeScript-specific rules
- Type-only imports and proper module boundaries
- Declaration files for third-party library integration
- Monorepo setup with project references and incremental builds
- CI/CD integration with type checking and testing
- Performance monitoring for compilation times
- Documentation generation from TSDoc comments
Create TypeScript applications that are not just type-safe but leverage the type system to prevent entire classes of runtime errors. Focus on expressing business logic through types.
---
name:typescript-developer
description:使用高级TypeScript特性、泛型和严格类型检查构建类型安全的应用。专精企业级TypeScript架构和类型系统设计。在复杂类型安全需求时主动使用。
model:sonnet
---
你是一位TypeScript专家,专注于使用高级类型系统特性构建健壮、类型安全的应用。
## TypeScript精通技能 / TypeScript Mastery
-高级类型系统(条件类型、映射类型、模板字面量类型)
-带约束和推断的泛型编程
-严格的TypeScript配置和编译器选项
-声明合并和模块增强
-工具类型和自定义类型转换
-品牌类型和名义类型模式
-类型守卫和可辨识联合
-装饰器模式和元数据反射
## 类型安全理念 / Type Safety Philosophy
1.严格的TypeScript配置,绝不妥协
2.全面的类型覆盖,零any类型
3.用于领域特定验证的品牌类型
4.使用可辨识联合进行穷举模式匹配
5.为可重用、类型安全的API使用泛型约束
6.使用Result/Either模式进行正确的错误建模
7.带编译时保证的运行时类型验证
8.接口优先的类型驱动开发
## 高级模式 / Advanced Patterns
-使用条件类型模拟高阶类型
-用于编译时状态跟踪的幻象类型
-使用递归条件类型进行类型级编程
-带流畅接口和类型安全的构建器模式
-带类型安全容器模式的依赖注入
-带强类型事件流的事件溯源
-带穷举状态转换的状态机
-使用OpenAPI和类型安全生成API客户端
## 企业标准 / Enterprise Standards
-启用严格规则的全面tsconfig.json配置
-集成TypeScript特定规则的ESLint
-仅类型导入和正确的模块边界
-第三方库集成的声明文件
-带项目引用和增量构建的Monorepo设置
-带类型检查和测试的CI/CD集成
-编译时间的性能监控
-从TSDoc注释生成文档
创建的TypeScript应用不仅类型安全,还要利用类型系统防止整类运行时错误。
专注于通过类型表达业务逻辑。
// 1. 什么是条件类型?
// 就像编程中的if-else,但是用于类型
type IsString<T> = T extendsstring ? true : false;
type Test1 = IsString<"hello">; // true
type Test2 = IsString<123>; // false
// 2. 什么是映射类型?
// 就像数组的map,但是用于对象类型
type Readonly<T> = {
readonly [K in keyof T]: T[K];
};
// 3. 什么是品牌类型?
// 给基础类型加上"标签",防止混用
type USD = number & { brand: 'USD' };
type EUR = number & { brand: 'EUR' };
function convertCurrency(amount: USD): EUR {
// 防止直接传入普通number
return (amount * 0.85) as EUR;
}
// 4. 什么是类型守卫?
// 帮助TypeScript理解运行时的类型
function isUser(obj: any): obj is User {
return'id'in obj && 'email'in obj;
}
if (isUser(data)) {
// TypeScript知道这里data是User类型
console.log(data.email);
}
# 在Claude Code中输入
/agents
选择上面的英文版或中文版配置,完整粘贴
TypeScript开发需要的权限:
建议选择 💙 蓝色(TypeScript的标志色),保存配置
输入指令:
创建一个类型安全的状态管理系统,要有完整的类型推导
TypeScript子代理输出:
// store.ts - 类型安全的状态管理系统
/**
* 类型安全的状态管理系统
* 支持时间旅行、中间件、类型推导
*/
// 基础类型定义
type DeepReadonly<T> = {
readonly [P in keyof T]: T[P] extends object ? DeepReadonly<T[P]> : T[P];
};
type DeepPartial<T> = {
[P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
};
// Action类型系统
interface Action<T = any> {
type: string;
payload?: T;
meta?: any;
error?: boolean;
}
// Action创建器类型
interface ActionCreator<P = void, T extends string = string> {
type: T;
(payload: P): Action<P> & { type: T };
match(action: Action): action is Action<P> & { type: T };
}
// 创建类型安全的Action创建器
function createAction<P = void, T extends string = string>(
type: T
): ActionCreator<P, T> {
const actionCreator = (payload: P) => ({
type,
payload
});
actionCreator.type = type;
actionCreator.match = (action: Action): action is Action<P> & { type: T } => {
return action.type === type;
};
return actionCreator as ActionCreator<P, T>;
}
// Reducer类型
type Reducer<S = any, A extends Action = Action> = (
state: S | undefined,
action: A
) => S;
// Store接口
interface Store<S = any, A extends Action = Action> {
getState(): DeepReadonly<S>;
dispatch<T extends A>(action: T): T;
subscribe(listener: (state: S) =>void): () =>void;
replaceReducer(nextReducer: Reducer<S, A>): void;
}
// 中间件类型
interface Middleware<S = any, A extends Action = Action> {
(store: MiddlewareAPI<S, A>): (
next: Dispatch<A>
) => (action: A) =>any;
}
interface MiddlewareAPI<S = any, A extends Action = Action> {
dispatch: Dispatch<A>;
getState(): S;
}
type Dispatch<A extends Action = Action> = <T extends A>(action: T) => T;
// 高级Store实现
class TypedStore<S, A extends Action = Action> implements Store<S, A> {
private state: S;
private reducer: Reducer<S, A>;
private listeners: Set<(state: S) =>void> = new Set();
private middlewares: Middleware<S, A>[] = [];
private isDispatching = false;
constructor(
reducer: Reducer<S, A>,
initialState?: S,
middlewares: Middleware<S, A>[] = []
) {
this.reducer = reducer;
this.state = initialState ?? reducer(undefined, { type: '@@INIT' } as A);
this.middlewares = middlewares;
}
getState(): DeepReadonly<S> {
if (this.isDispatching) {
thrownewError('Cannot call getState while dispatching');
}
returnthis.state as DeepReadonly<S>;
}
dispatch = <T extends A>(action: T): T => {
if (this.isDispatching) {
thrownewError('Cannot dispatch while dispatching');
}
// 应用中间件
const chain = this.middlewares.map(middleware =>
middleware({
getState: () =>this.state,
dispatch: this.dispatch
})
);
let dispatch: Dispatch<A> = (action) => {
this.isDispatching = true;
try {
this.state = this.reducer(this.state, action);
this.notifyListeners();
return action;
} finally {
this.isDispatching = false;
}
};
// 组合中间件
for (let i = chain.length - 1; i >= 0; i--) {
dispatch = chain[i](dispatch);
}
return dispatch(action) as T;
};
subscribe(listener: (state: S) =>void): () =>void {
this.listeners.add(listener);
return() => {
this.listeners.delete(listener);
};
}
replaceReducer(nextReducer: Reducer<S, A>): void {
this.reducer = nextReducer;
this.dispatch({ type: '@@REPLACE' } as A);
}
private notifyListeners(): void {
this.listeners.forEach(listener => listener(this.state));
}
}
// 组合Reducers工具
type CombinedState<S> = {
[K in keyof S]: S[K];
};
function combineReducers<S extends Record<string, any>>(
reducers: { [K in keyof S]: Reducer<S[K], any> }
): Reducer<CombinedState<S>> {
return(state = {} as CombinedState<S>, action) => {
const nextState = {} as CombinedState<S>;
let hasChanged = false;
for (const key in reducers) {
const reducer = reducers[key];
const previousStateForKey = state[key];
const nextStateForKey = reducer(previousStateForKey, action);
nextState[key] = nextStateForKey;
hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
}
return hasChanged ? nextState : state;
};
}
// 使用示例
// 定义状态类型
interface TodoState {
items: Todo[];
filter: 'all' | 'active' | 'completed';
}
interface Todo {
id: string;
text: string;
completed: boolean;
}
// 创建类型安全的Actions
const addTodo = createAction<{ text: string }>('ADD_TODO');
const toggleTodo = createAction<{ id: string }>('TOGGLE_TODO');
const setFilter = createAction<TodoState['filter']>('SET_FILTER');
// 类型安全的Reducer
const todoReducer: Reducer<TodoState> = (
state = { items: [], filter: 'all' },
action
) => {
if (addTodo.match(action)) {
return {
...state,
items: [
...state.items,
{
id: Date.now().toString(),
text: action.payload.text,
completed: false
}
]
};
}
if (toggleTodo.match(action)) {
return {
...state,
items: state.items.map(todo =>
todo.id === action.payload.id
? { ...todo, completed: !todo.completed }
: todo
)
};
}
if (setFilter.match(action)) {
return {
...state,
filter: action.payload
};
}
return state;
};
// 创建Store
const store = new TypedStore(todoReducer);
// 类型安全的使用
store.dispatch(addTodo({ text: 'Learn TypeScript' }));
store.dispatch(toggleTodo({ id: '123' }));
// store.dispatch(addTodo({ wrong: 'type' })); // 编译错误!
const state = store.getState();
// state.items = []; // 编译错误!只读
export { TypedStore, createAction, combineReducers };
看看TypeScript子代理自动实现了什么:
输入:
创建一个类型安全的API客户端,自动推导请求和响应类型
TypeScript子代理输出:
// apiClient.ts - 类型安全的API客户端
/**
* 类型安全的API客户端
* 自动推导请求/响应类型,编译时验证
*/
// API定义类型系统
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
interface ApiEndpoint
TPath extends string = string,
TMethod extends HttpMethod = HttpMethod,
TParams = unknown,
TBody = unknown,
TResponse = unknown
> {
path: TPath;
method: TMethod;
params?: TParams;
body?: TBody;
response: TResponse;
}
// 路径参数提取
type ExtractRouteParams<T extendsstring> =
T extends`${infer _Start}:${infer Param}/${infer Rest}`
? { [K in Param]: string } & ExtractRouteParams<Rest>
: T extends`${infer _Start}:${infer Param}`
? { [K in Param]: string }
: {};
// API定义
interface ApiDefinition {
'/users': {
GET: ApiEndpoint
'/users',
'GET',
{ page?: number; limit?: number },
never,
{ users: User[]; total: number }
>;
POST: ApiEndpoint
'/users',
'POST',
never,
CreateUserDto,
User
>;
};
'/users/:id': {
GET: ApiEndpoint
'/users/:id',
'GET',
ExtractRouteParams<'/users/:id'>,
never,
User
>;
PUT: ApiEndpoint
'/users/:id',
'PUT',
ExtractRouteParams<'/users/:id'>,
UpdateUserDto,
User
>;
DELETE: ApiEndpoint
'/users/:id',
'DELETE',
ExtractRouteParams<'/users/:id'>,
never,
void
>;
};
}
// DTO类型
interface User {
id: string;
email: string;
name: string;
role: 'admin' | 'user';
createdAt: Date;
}
interface CreateUserDto {
email: string;
name: string;
password: string;
}
interface UpdateUserDto {
name?: string;
role?: 'admin' | 'user';
}
// 请求配置
interface RequestConfig<TParams = any, TBody = any> {
params?: TParams;
body?: TBody;
headers?: Record<string, string>;
signal?: AbortSignal;
}
// 类型安全的API客户端
class TypeSafeApiClient<TApi extends Record<string, any>> {
constructor(private baseUrl: string, private defaultHeaders?: Record<string, string>) {}
async request
TPath extends keyof TApi,
TMethod extends keyof TApi[TPath]
>(
path: TPath,
method: TMethod,
config?: RequestConfig
TApi[TPath][TMethod]['params'],
TApi[TPath][TMethod]['body']
>
): Promise<TApi[TPath][TMethod]['response']> {
const endpoint = `${this.baseUrl}${String(path)}`;
const url = this.buildUrl(endpoint, config?.params);
const response = await fetch(url, {
method: String(method),
headers: {
'Content-Type': 'application/json',
...this.defaultHeaders,
...config?.headers
},
body: config?.body ? JSON.stringify(config.body) : undefined,
signal: config?.signal
});
if (!response.ok) {
thrownew ApiError(response.status, response.statusText);
}
return response.json();
}
// 便捷方法
get<TPath extends keyof TApi>(
path: TPath,
config?: RequestConfig<TApi[TPath]['GET']['params'], never>
): Promise<TApi[TPath]['GET']['response']> {
returnthis.request(path, 'GET', config);
}
post<TPath extends keyof TApi>(
path: TPath,
body: TApi[TPath]['POST']['body'],
config?: RequestConfig<TApi[TPath]['POST']['params'], never>
): Promise<TApi[TPath]['POST']['response']> {
returnthis.request(path, 'POST', { ...config, body });
}
put<TPath extends keyof TApi>(
path: TPath,
body: TApi[TPath]['PUT']['body'],
config?: RequestConfig<TApi[TPath]['PUT']['params'], never>
): Promise<TApi[TPath]['PUT']['response']> {
returnthis.request(path, 'PUT', { ...config, body });
}
delete<TPath extends keyof TApi>(
path: TPath,
config?: RequestConfig<TApi[TPath]['DELETE']['params'], never>
): Promise<TApi[TPath]['DELETE']['response']> {
returnthis.request(path, 'DELETE', config);
}
private buildUrl(endpoint: string, params?: any): string {
if (!params) return endpoint;
// 处理路径参数
let url = endpoint;
for (const [key, value] of Object.entries(params)) {
url = url.replace(`:${key}`, String(value));
}
// 处理查询参数
const queryParams = new URLSearchParams();
for (const [key, value] of Object.entries(params)) {
if (!endpoint.includes(`:${key}`)) {
queryParams.append(key, String(value));
}
}
const queryString = queryParams.toString();
return queryString ? `${url}?${queryString}` : url;
}
}
// 错误处理
class ApiError extendsError {
constructor(public status: number, public statusText: string) {
super(`API Error: ${status} ${statusText}`);
this.name = 'ApiError';
}
}
// 使用示例
const api = new TypeSafeApiClient<ApiDefinition>('https://api.example.com');
// 类型安全的API调用
asyncfunction example() {
// GET /users - 自动推导响应类型
const { users, total } = await api.get('/users', {
params: { page: 1, limit: 10 }
});
// POST /users - 强制要求body类型
const newUser = await api.post('/users', {
email: 'test@example.com',
name: 'Test User',
password: 'secure123'
});
// PUT /users/:id - 路径参数自动推导
const updatedUser = await api.put('/users/:id', {
name: 'Updated Name'
}, {
params: { id: '123' }
});
// 编译错误示例
// await api.post('/users', { wrong: 'field' }); // 错误!
// await api.get('/nonexistent'); // 错误!
}
export { TypeSafeApiClient, ApiError };
React + TypeScript版:
## TypeScript Mastery
- React 18类型定义
- Props类型推导
- Hooks类型安全
- Context类型推导
- 高阶组件类型
Node.js + TypeScript版:
## TypeScript Mastery
- Express类型定义
- Prisma类型生成
- tRPC端到端类型安全
- Zod运行时验证
## Team Standards
- 命名规范:接口I前缀,类型T前缀
- 文件组织:类型定义独立文件
- 导入规范:类型导入使用type关键字
- 注释要求:TSDoc格式
- 测试覆盖:类型测试使用tsd
触发关键词:
子代理会自动:
// 1. 查找@types包
npm install --save-dev @types/lodash
// 2. 创建声明文件
declare module 'untyped-library' {
export function someFunction(param: string): void;
}
// 3. 使用any escape hatch(最后选择)
const lib = require('untyped-library') as any;
子代理会配置:
{
"compilerOptions": {
"incremental": true,
"tsBuildInfoFile": ".tsbuildinfo",
"skipLibCheck": true
}
}
评估指标 | 通用Claude | TypeScript子代理 | 提升幅度 |
---|---|---|---|
类型覆盖率 | 40% | 100% | +150% |
运行时错误 | 常见 | 几乎为零 | -95% |
代码可维护性 | 中等 | 极高 | +200% |
开发效率 | 基础 | 高效 | +180% |
重构安全性 | 危险 | 安全 | +300% |
这个TypeScript开发子代理带来的价值:
记住:TypeScript不是给JavaScript加注释,而是用类型系统构建更可靠的应用。这个子代理帮你发挥TypeScript的全部潜力。
/agents
创建代理现在就配置你的TypeScript开发子代理,让每一行代码都类型安全!💙🛡️
#子代理 #ClaudeCode #AI #程序员 #前端达人