moai-lang-typescript

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Quick Reference (30 seconds)

快速参考(30秒)

TypeScript 5.9+ Development Specialist - Modern TypeScript with React 19, Next.js 16, and type-safe API patterns.
Auto-Triggers: Files with .ts, .tsx, .mts, or .cts extensions, TypeScript configurations, React or Next.js projects
Core Stack:
  • TypeScript 5.9: Deferred module evaluation, decorators, satisfies operator
  • React 19: Server Components, use hook, Actions, concurrent features
  • Next.js 16: App Router, Server Actions, middleware, ISR/SSG/SSR
  • Type-Safe APIs: tRPC 11, Zod 3.23, tanstack-query
  • Testing: Vitest, React Testing Library, Playwright
Quick Commands:
Create Next.js 16 project using npx create-next-app with latest, typescript, tailwind, and app flags. Install type-safe API stack with npm install for trpc server, client, react-query, zod, and tanstack react-query. Install testing stack with npm install D flag for vitest, testing-library react, and playwright test.

TypeScript 5.9+开发专家 - 结合React 19、Next.js 16的现代TypeScript及类型安全API模式。
自动触发场景:扩展名为.ts、.tsx、.mts或.cts的文件,TypeScript配置,React或Next.js项目
核心技术栈:
  • TypeScript 5.9:延迟模块评估、装饰器、satisfies操作符
  • React 19:服务器组件、use钩子、Actions、并发特性
  • Next.js 16:App Router、Server Actions、中间件、ISR/SSG/SSR
  • 类型安全API:tRPC 11、Zod 3.23、tanstack-query
  • 测试:Vitest、React Testing Library、Playwright
快速命令:
使用npx create-next-app创建Next.js 16项目,带上latest、typescript、tailwind和app参数。通过npm install安装类型安全API栈,包括trpc server、client、react-query、zod和tanstack react-query。使用npm install -D安装测试栈,包括vitest、testing-library react和playwright test。

Implementation Guide (5 minutes)

实现指南(5分钟)

TypeScript 5.9 Key Features

TypeScript 5.9核心特性

Satisfies Operator for Type Checking Without Widening:
Define Colors type as union of red, green, and blue string literals. Create palette object with red as number array, green as hex string, and blue as number array. Apply satisfies operator with Record of Colors to string or number array. Now palette.red can use map method because it is inferred as number array, and palette.green can use toUpperCase because it is inferred as string.
Deferred Module Evaluation:
Use import defer with asterisk as namespace from heavy module path. In function that needs the module, access namespace property which loads module on first use.
Modern Decorators Stage 3:
Create logged function decorator that takes target function and ClassMethodDecoratorContext. Return function that logs method name then calls target with apply. Apply logged decorator to class method that fetches data.
用于类型检查且不拓宽类型的Satisfies操作符:
定义Colors类型为red、green、blue字符串字面量的联合类型。创建palette对象,其中red为数字数组、green为十六进制字符串、blue为数字数组。对Record<Colors, string | number[]>应用satisfies操作符。现在palette.red可以使用map方法,因为它被推断为数字数组,而palette.green可以使用toUpperCase方法,因为它被推断为字符串。
延迟模块评估:
使用import defer(* as namespace) from '重型模块路径'语法。在需要该模块的函数中,访问namespace属性,模块会在首次使用时加载。
Stage 3现代装饰器:
创建logged函数装饰器,接收目标函数和ClassMethodDecoratorContext。返回一个先记录方法名称再调用目标函数的函数。将logged装饰器应用于获取数据的类方法。

React 19 Patterns

React 19模式

Server Components Default in App Router:
For page component in app/users/[id]/page.tsx, define PageProps interface with params as Promise of object containing id string. Create async default function that awaits params, queries database for user, calls notFound if not found, and returns main element with user name.
use Hook for Unwrapping Promises and Context:
In client component marked with use client directive, import use from react. Create UserProfile component that takes userPromise prop as Promise of User type. Call use hook with the promise to suspend until resolved. Return div with user name.
Actions for Form Handling with Server Functions:
In server actions file marked with use server directive, import revalidatePath. Define CreateUserSchema with zod for name and email validation. Create async createUser function that takes FormData, parses with schema, creates user in database, and revalidates path.
useActionState for Form Status:
In client component, import useActionState. Create form component that destructures state, action, and isPending from useActionState called with createUser action. Return form with action prop, input disabled when pending, button with dynamic text, and error message from state.
App Router中默认使用服务器组件:
对于app/users/[id]/page.tsx中的页面组件,定义PageProps接口,其中params为包含id字符串的对象的Promise。创建异步默认函数,等待params解析,查询数据库获取用户信息,若未找到则调用notFound,最后返回包含用户名的main元素。
用于解包Promise和Context的use钩子:
在标记了'use client'指令的客户端组件中,从react导入use。创建UserProfile组件,接收类型为Promise<User>的userPromise属性。调用use钩子传入该promise,组件会挂起直到Promise解析完成。返回包含用户名的div。
基于服务器函数的表单处理Actions:
在标记了'use server'指令的服务器actions文件中,导入revalidatePath。使用zod定义CreateUserSchema,对name和email进行验证。创建异步createUser函数,接收FormData,用schema解析数据,在数据库中创建用户,然后重新验证路径。
用于表单状态管理的useActionState:
在客户端组件中,导入useActionState。创建表单组件,从调用useActionState(传入createUser action)的结果中解构state、action和isPending。返回设置了action属性的表单,pending状态时禁用输入,按钮文本动态变化,并显示来自state的错误信息。

Next.js 16 App Router

Next.js 16 App Router

Route Structure:
The app directory contains layout.tsx for root layout, page.tsx for home route, loading.tsx for loading UI, error.tsx for error boundary, and api/route.ts for API routes. Subdirectories like users contain page.tsx for list and [id]/page.tsx for dynamic routes. Route groups use parentheses like (marketing)/about/page.tsx.
Metadata API:
Import Metadata type. Export metadata object with title as object containing default and template, and description string. Export async generateMetadata function that takes params, awaits params, fetches user, and returns object with title set to user name.
Server Actions with Validation:
In server file, import zod, revalidatePath, and redirect. Define UpdateUserSchema with id, name, and email validation. Create async updateUser function taking prevState and formData. Parse with safeParse, return errors if failed, update database, revalidate path, and redirect.
路由结构:
app目录包含根布局layout.tsx、首页路由page.tsx、加载UI loading.tsx、错误边界error.tsx,以及API路由api/route.ts。子目录如users包含列表页page.tsx和动态路由[id]/page.tsx。路由组使用括号表示,如(marketing)/about/page.tsx。
元数据API:
导入Metadata类型。导出metadata对象,包含title(含default和template的对象)和description字符串。导出异步generateMetadata函数,接收params,等待其解析,获取用户信息,返回设置了用户名为title的对象。
带验证的Server Actions:
在服务器文件中,导入zod、revalidatePath和redirect。定义UpdateUserSchema,对id、name和email进行验证。创建异步updateUser函数,接收prevState和formData。使用safeParse解析,若失败则返回错误信息,更新数据库,重新验证路径,然后跳转。

Type-Safe APIs with tRPC

基于tRPC的类型安全API

Server Setup:
Import initTRPC and TRPCError from trpc server. Create t by calling initTRPC.context with Context type then create. Export router, publicProcedure, and protectedProcedure from t. The protectedProcedure uses middleware that checks session user and throws UNAUTHORIZED error if missing.
Router Definition:
Import zod. Create userRouter with router function. Define getById procedure using publicProcedure with input schema for id as uuid string, and query that finds user by id. Define create procedure using protectedProcedure with input schema for name and email, and mutation that creates user.
Client Usage:
In client component, create UserList function that calls trpc.user.list.useQuery with page parameter. Destructure data and isLoading. Create mutation with trpc.user.create.useMutation. Return loading state or list of users.
服务器端配置:
从trpc/server导入initTRPC和TRPCError。通过调用initTRPC.context<Context>().create()创建t。从t导出router、publicProcedure和protectedProcedure。protectedProcedure使用中间件检查会话用户,若不存在则抛出UNAUTHORIZED错误。
路由定义:
导入zod。使用router函数创建userRouter。定义getById过程,使用publicProcedure并传入id为uuid字符串的输入schema,查询逻辑为根据id查找用户。定义create过程,使用protectedProcedure并传入name和email的输入schema,变更逻辑为创建用户。
客户端使用:
在客户端组件中,创建UserList函数,调用trpc.user.list.useQuery并传入page参数。解构data和isLoading。使用trpc.user.create.useMutation创建变更操作。返回加载状态或用户列表。

Zod Schema Patterns

Zod Schema模式

Complex Validation:
Create UserSchema with z.object containing id as uuid string, name with min and max length, email as email format, role as enum of admin, user, and guest, and createdAt with coerce.date. Apply strict method. Infer User type from schema. Create CreateUserSchema by omitting id and createdAt, extending with password and confirmPassword, and adding refine for password match validation with custom message and path.
复杂验证:
创建UserSchema,使用z.object包含id(uuid字符串)、name(指定最小和最大长度)、email(邮箱格式)、role(admin、user、guest枚举)和createdAt(coerce.date)。调用strict方法。从schema中推断User类型。创建CreateUserSchema,通过omit移除id和createdAt,extend添加password和confirmPassword,并添加refine验证密码匹配,自定义错误信息和路径。

State Management

状态管理

Zustand for Client State:
Import create from zustand and middleware. Define AuthState interface with user as User or null, login method, and logout method. Create useAuthStore with create function wrapped in devtools and persist middleware. Set initial user to null, login sets user, logout sets user to null. Persist uses auth-storage name.
Jotai for Atomic State:
Import atom from jotai and atomWithStorage from jotai/utils. Create countAtom with initial value 0. Create doubleCountAtom as derived atom that gets countAtom and multiplies by 2. Create themeAtom with atomWithStorage for light or dark theme persisted to storage.

用于客户端状态的Zustand:
从zustand和middleware导入create。定义AuthState接口,包含user(User或null)、login方法和logout方法。使用包裹了devtools和persist中间件的create函数创建useAuthStore。初始user设为null,login设置user,logout将user设为null。Persist使用auth-storage作为存储名称。
用于原子状态的Jotai:
从jotai导入atom,从jotai/utils导入atomWithStorage。创建countAtom,初始值为0。创建doubleCountAtom作为派生atom,获取countAtom的值并乘以2。创建themeAtom,使用atomWithStorage存储light或dark主题,持久化到存储中。

Advanced Patterns

高级模式

For comprehensive documentation including advanced TypeScript patterns, performance optimization, testing strategies, and deployment configurations, see:
  • reference.md for complete API reference, Context7 library mappings, and advanced type patterns
  • examples.md for production-ready code examples, full-stack patterns, and testing templates
如需包含高级TypeScript模式、性能优化、测试策略和部署配置的完整文档,请参考:
  • reference.md:完整API参考、Context7库映射和高级类型模式
  • examples.md:生产就绪的代码示例、全栈模式和测试模板

Context7 Integration

Context7集成

For TypeScript documentation, use microsoft/TypeScript with decorators satisfies topics. For React 19, use facebook/react with server-components use-hook. For Next.js 16, use vercel/next.js with app-router server-actions. For tRPC, use trpc/trpc with procedures middleware. For Zod, use colinhacks/zod with schema validation.

TypeScript文档:使用microsoft/TypeScript的decorators、satisfies相关主题。React 19:使用facebook/react的server-components、use-hook相关主题。Next.js 16:使用vercel/next.js的app-router、server-actions相关主题。tRPC:使用trpc/trpc的procedures、middleware相关主题。Zod:使用colinhacks/zod的schema、validation相关主题。

Works Well With

适配工具

  • moai-domain-frontend for UI components and styling patterns
  • moai-domain-backend for API design and database integration
  • moai-library-shadcn for component library integration
  • moai-workflow-testing for testing strategies and patterns
  • moai-foundation-quality for code quality standards
  • moai-essentials-debug for debugging TypeScript applications

  • moai-domain-frontend:UI组件和样式模式
  • moai-domain-backend:API设计和数据库集成
  • moai-library-shadcn:组件库集成
  • moai-workflow-testing:测试策略和模式
  • moai-foundation-quality:代码质量标准
  • moai-essentials-debug:TypeScript应用调试

Quick Troubleshooting

快速故障排除

TypeScript Errors:
Run npx tsc with noEmit flag for type check only. Run npx tsc with generateTrace flag and output directory for performance trace.
React and Next.js Issues:
Run npm run build to check for build errors. Run npx next lint for ESLint check. Delete .next directory and run npm run dev to clear cache.
Type Safety Patterns:
Create assertNever function taking never type parameter that throws error for unexpected values, used in exhaustive switch statements. Create type guard function isUser that checks if value is object with id property and returns type predicate.

Last Updated: 2026-01-11 Status: Active (v1.1.0)
TypeScript错误:
运行npx tsc --noEmit仅进行类型检查。运行npx tsc --generateTrace <输出目录>生成性能跟踪报告。
React和Next.js问题:
运行npm run build检查构建错误。运行npx next lint进行ESLint检查。删除.next目录并运行npm run dev清除缓存。
类型安全模式:
创建assertNever函数,接收never类型参数,对意外值抛出错误,用于穷尽switch语句。创建类型守卫函数isUser,检查值是否为包含id属性的对象,并返回类型断言。

最后更新:2026-01-11 状态:活跃(v1.1.0)