typescript-core
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTypeScript Core Patterns
TypeScript核心模式
Modern TypeScript development patterns for type safety, runtime validation, and optimal configuration.
面向类型安全、运行时验证与最优配置的现代TypeScript开发模式。
Quick Start
快速开始
New Project: Use 2025 tsconfig → Enable + → Choose Zod for validation
strictnoUncheckedIndexedAccessExisting Project: Enable initially → Fix with → Add
strict: falseanyunknownnoUncheckedIndexedAccessAPI Development: Zod schemas at boundaries → for types → for routes
z.infer<typeof Schema>satisfiesLibrary Development: Enable → Use type parameters → See advanced-patterns-2025.md
declaration: trueconst新项目: 使用2025版tsconfig → 启用 + → 选择Zod进行验证
strictnoUncheckedIndexedAccess现有项目: 初始启用 → 用替换 → 添加
strict: falseunknownanynoUncheckedIndexedAccessAPI开发: 在边界处使用Zod模式 → 用获取类型 → 为路由使用
z.infer<typeof Schema>satisfies库开发: 启用 → 使用类型参数 → 查看advanced-patterns-2025.md
declaration: trueconstQuick Reference
快速参考
tsconfig.json 2025 Baseline
tsconfig.json 2025基准配置
json
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"verbatimModuleSyntax": true,
"isolatedModules": true,
"skipLibCheck": true,
"declaration": true,
"declarationMap": true
}
}json
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"verbatimModuleSyntax": true,
"isolatedModules": true,
"skipLibCheck": true,
"declaration": true,
"declarationMap": true
}
}Key Compiler Options
关键编译器选项
| Option | Purpose | When to Enable |
|---|---|---|
| Forces null checks on array/object access | Always for safety |
| Distinguishes | APIs with optional fields |
| Enforces explicit type-only imports | ESM projects |
| Node.js 22+ native TS support | Type stripping environments |
| 选项 | 用途 | 启用时机 |
|---|---|---|
| 强制对数组/对象访问进行空值检查 | 为了安全始终启用 |
| 区分 | 带有可选字段的API |
| 强制执行显式类型仅导入 | ESM项目 |
| Node.js 22+原生TS支持 | 类型剥离环境 |
Local Baselines
本地基准配置
See for repo-specific tsconfig patterns (CommonJS CLI, NodeNext strict, Next.js bundler).
references/configuration.md查看获取仓库专属的tsconfig模式(CommonJS CLI、NodeNext严格模式、Next.js打包器)。
references/configuration.mdCore Type Patterns
核心类型模式
Const Type Parameters
Const类型参数
Preserve literal types through generic functions:
typescript
function createConfig<const T extends Record<string, unknown>>(config: T): T {
return config;
}
const config = createConfig({
apiUrl: "https://api.example.com",
timeout: 5000
});
// Type: { readonly apiUrl: "https://api.example.com"; readonly timeout: 5000 }通过泛型函数保留字面量类型:
typescript
function createConfig<const T extends Record<string, unknown>>(config: T): T {
return config;
}
const config = createConfig({
apiUrl: "https://api.example.com",
timeout: 5000
});
// 类型:{ readonly apiUrl: "https://api.example.com"; readonly timeout: 5000 }Satisfies Operator
Satisfies操作符
Validate against a type while preserving literal inference:
typescript
type Route = { path: string; children?: Routes };
type Routes = Record<string, Route>;
const routes = {
AUTH: { path: "/auth" },
HOME: { path: "/" }
} satisfies Routes;
routes.AUTH.path; // Type: "/auth" (literal preserved)
routes.NONEXISTENT; // ❌ Type error验证类型的同时保留字面量推断:
typescript
type Route = { path: string; children?: Routes };
type Routes = Record<string, Route>;
const routes = {
AUTH: { path: "/auth" },
HOME: { path: "/" }
} satisfies Routes;
routes.AUTH.path; // 类型:"/auth"(字面量保留)
routes.NONEXISTENT; // ❌ 类型错误Template Literal Types
模板字面量类型
Type-safe string manipulation and route extraction:
typescript
type ExtractParams<T extends string> =
T extends `${string}:${infer Param}/${infer Rest}`
? Param | ExtractParams<Rest>
: T extends `${string}:${infer Param}`
? Param
: never;
type Params = ExtractParams<"/users/:id/posts/:postId">; // "id" | "postId"类型安全的字符串操作与路由参数提取:
typescript
type ExtractParams<T extends string> =
T extends `${string}:${infer Param}/${infer Rest}`
? Param | ExtractParams<Rest>
: T extends `${string}:${infer Param}`
? Param
: never;
type Params = ExtractParams<"/users/:id/posts/:postId">; // "id" | "postId"Discriminated Unions with Exhaustiveness
带穷尽性检查的可区分联合类型
typescript
type Result<T, E = Error> =
| { success: true; data: T }
| { success: false; error: E };
function handleResult<T>(result: Result<T>): T {
if (result.success) return result.data;
throw result.error;
}
// Exhaustiveness checking
type Action =
| { type: 'create'; payload: string }
| { type: 'delete'; id: number };
function handle(action: Action) {
switch (action.type) {
case 'create': return action.payload;
case 'delete': return action.id;
default: {
const _exhaustive: never = action;
throw new Error(`Unhandled: ${_exhaustive}`);
}
}
}typescript
type Result<T, E = Error> =
| { success: true; data: T }
| { success: false; error: E };
function handleResult<T>(result: Result<T>): T {
if (result.success) return result.data;
throw result.error;
}
// 穷尽性检查
type Action =
| { type: 'create'; payload: string }
| { type: 'delete'; id: number };
function handle(action: Action) {
switch (action.type) {
case 'create': return action.payload;
case 'delete': return action.id;
default: {
const _exhaustive: never = action;
throw new Error(`未处理的操作:${_exhaustive}`);
}
}
}Runtime Validation
运行时验证
TypeScript types disappear at runtime. Use validation libraries for external data (APIs, forms, config files).
TypeScript类型在运行时会消失。对外部数据(API、表单、配置文件)使用验证库。
Quick Comparison
快速对比
| Library | Bundle Size | Speed | Best For |
|---|---|---|---|
| Zod | ~13.5kB | Baseline | Full-stack apps, tRPC integration |
| TypeBox | ~8kB | ~10x faster | OpenAPI, performance-critical |
| Valibot | ~1.4kB | ~2x faster | Edge functions, minimal bundles |
| 库 | 包体积 | 速度 | 最佳适用场景 |
|---|---|---|---|
| Zod | ~13.5kB | 基准 | 全栈应用、tRPC集成 |
| TypeBox | ~8kB | ~10倍快 | OpenAPI、性能关键场景 |
| Valibot | ~1.4kB | ~2倍快 | Edge函数、最小包体积场景 |
Basic Pattern (Zod)
基础模式(Zod)
typescript
import { z } from "zod";
const UserSchema = z.object({
id: z.string().uuid(),
email: z.string().email(),
role: z.enum(["admin", "user", "guest"]),
});
type User = z.infer<typeof UserSchema>;
// Validate external data
function parseUser(input: unknown): User {
return UserSchema.parse(input);
}→ See runtime-validation.md for complete Zod, TypeBox, and Valibot patterns
typescript
import { z } from "zod";
const UserSchema = z.object({
id: z.string().uuid(),
email: z.string().email(),
role: z.enum(["admin", "user", "guest"]),
});
type User = z.infer<typeof UserSchema>;
// 验证外部数据
function parseUser(input: unknown): User {
return UserSchema.parse(input);
}→ 查看runtime-validation.md获取完整的Zod、TypeBox与Valibot模式
Decision Support
决策支持
Quick Decision Guide
快速决策指南
Need to choose between vs ?
typeinterface- Public API / library types →
interface - Union types / mapped types →
type - Simple object shapes → (default)
interface
Need generics or union types?
- Output type depends on input type → Generics
- Fixed set of known types → Union types
- Building reusable data structures → Generics
Dealing with unknown data?
- External data (API, user input) → (type-safe)
unknown - Rapid prototyping / migration → (temporarily)
any
Need runtime validation?
- Full-stack TypeScript with tRPC → Zod
- OpenAPI / high performance → TypeBox
- Edge functions / minimal bundle → Valibot
→ See decision-trees.md for comprehensive decision frameworks
需要在与之间选择?
typeinterface- 公共API / 库类型 →
interface - 联合类型 / 映射类型 →
type - 简单对象结构 → (默认选择)
interface
需要泛型或联合类型?
- 输出类型依赖输入类型 → 泛型
- 固定的已知类型集合 → 联合类型
- 构建可复用数据结构 → 泛型
处理未知数据?
- 外部数据(API、用户输入) → (类型安全)
unknown - 快速原型开发 / 迁移 → (临时使用)
any
需要运行时验证?
- 带tRPC的全栈TypeScript → Zod
- OpenAPI / 高性能场景 → TypeBox
- Edge函数 / 最小包体积 → Valibot
→ 查看decision-trees.md获取全面的决策框架
Troubleshooting
故障排除
Common Issues Quick Reference
常见问题快速参考
Property does not exist on type → Define proper interface or use optional properties
Type is not assignable → Fix property types or use runtime validation (Zod)
Object is possibly 'undefined' → Use optional chaining () or type guards
?.Cannot find module → Check file extensions (.js for ESM) and module resolution
Slow compilation → Enable , use , consider esbuild/swc
incrementalskipLibCheck→ See troubleshooting.md for detailed solutions with examples
属性在类型上不存在 → 定义正确的接口或使用可选属性
类型不可分配 → 修复属性类型或使用运行时验证(Zod)
对象可能为'undefined' → 使用可选链()或类型守卫
?.无法找到模块 → 检查文件扩展名(ESM使用.js)与模块解析配置
编译缓慢 → 启用,使用,考虑esbuild/swc
incrementalskipLibCheck→ 查看troubleshooting.md获取带示例的详细解决方案
Navigation
导航
Detailed References
详细参考文档
-
📐 Advanced Types - Conditional types, mapped types, infer keyword, recursive types. Load when building complex type utilities or generic libraries.
-
⚙️ Configuration - Complete tsconfig.json guide, project references, monorepo patterns. Load when setting up new projects or optimizing builds.
-
🔒 Runtime Validation - Zod, TypeBox, Valibot deep patterns, error handling, integration strategies. Load when implementing API validation or form handling.
-
✨ Advanced Patterns 2025 - TypeScript 5.2+ features:keyword, stable decorators, import type behavior, satisfies with generics. Load when using modern language features.
using -
🌳 Decision Trees - Clear decision frameworks forvs
type, generics vs unions,interfacevsunknown, validation library selection, type narrowing strategies, and module resolution. Load when making TypeScript design decisions.any -
🔧 Troubleshooting - Common TypeScript errors and fixes, type inference issues, module resolution problems, tsconfig misconfigurations, build performance optimization, and type compatibility errors. Load when debugging TypeScript issues.
-
📐 高级类型 - 条件类型、映射类型、infer关键字、递归类型。构建复杂类型工具或泛型库时查看。
-
⚙️ 配置 - 完整的tsconfig.json指南、项目引用、单仓库模式。设置新项目或优化构建时查看。
-
🔒 运行时验证 - Zod、TypeBox、Valibot深度模式、错误处理、集成策略。实现API验证或表单处理时查看。
-
✨ 2025高级模式 - TypeScript 5.2+特性:关键字、稳定装饰器、导入类型行为、带泛型的satisfies。使用现代语言特性时查看。
using -
🌳 决策树 - 清晰的决策框架,涵盖vs
type、泛型vs联合类型、interfacevsunknown、验证库选择、类型收窄策略与模块解析。做TypeScript设计决策时查看。any -
🔧 故障排除 - 常见TypeScript错误与修复、类型推断问题、模块解析问题、tsconfig配置错误、构建性能优化与类型兼容性错误。调试TypeScript问题时查看。
Red Flags
警示信号
Stop and reconsider if:
- Using instead of
anyfor external dataunknown - Casting with without runtime validation
as - Disabling strict mode for convenience
- Using without clear justification
@ts-ignore - Index access without
noUncheckedIndexedAccess
若出现以下情况请停止并重新考虑:
- 对外部数据使用而非
anyunknown - 未进行运行时验证就使用类型断言
as - 为了方便禁用严格模式
- 无明确理由使用
@ts-ignore - 未启用就进行索引访问
noUncheckedIndexedAccess
Integration with Other Skills
与其他技能的集成
- nextjs-core: Type-safe Server Actions and route handlers
- nextjs-v16: Async API patterns and Cache Components typing
- mcp-builder: Zod schemas for MCP tool inputs
- nextjs-core: 类型安全的Server Actions与路由处理器
- nextjs-v16: 异步API模式与缓存组件类型定义
- mcp-builder: 为MCP工具输入使用Zod模式
Related Skills
相关技能
When using Core, these skills enhance your workflow:
- react: TypeScript with React: component typing, hooks, generics
- nextjs: TypeScript in Next.js: Server Components, Server Actions typing
- drizzle: Type-safe database queries with Drizzle ORM
- prisma: Prisma's generated TypeScript types for database schemas
[Full documentation available in these skills if deployed in your bundle]
使用核心技能时,以下技能可增强你的工作流:
- react: TypeScript与React结合:组件类型定义、Hooks、泛型
- nextjs: Next.js中的TypeScript:服务端组件、Server Actions类型定义
- drizzle: 用Drizzle ORM实现类型安全的数据库查询
- prisma: Prisma为数据库模式生成的TypeScript类型
[若在你的技能包中部署了这些技能,可查看完整文档]