typescript-core

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

TypeScript Core Patterns

TypeScript核心模式

Modern TypeScript development patterns for type safety, runtime validation, and optimal configuration.
面向类型安全、运行时验证与最优配置的现代TypeScript开发模式。

Quick Start

快速开始

New Project: Use 2025 tsconfig → Enable
strict
+
noUncheckedIndexedAccess
→ Choose Zod for validation
Existing Project: Enable
strict: false
initially → Fix
any
with
unknown
→ Add
noUncheckedIndexedAccess
API Development: Zod schemas at boundaries →
z.infer<typeof Schema>
for types →
satisfies
for routes
Library Development: Enable
declaration: true
→ Use
const
type parameters → See advanced-patterns-2025.md
新项目: 使用2025版tsconfig → 启用
strict
+
noUncheckedIndexedAccess
→ 选择Zod进行验证
现有项目: 初始启用
strict: false
→ 用
unknown
替换
any
→ 添加
noUncheckedIndexedAccess
API开发: 在边界处使用Zod模式 → 用
z.infer<typeof Schema>
获取类型 → 为路由使用
satisfies
库开发: 启用
declaration: true
→ 使用
const
类型参数 → 查看advanced-patterns-2025.md

Quick 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

关键编译器选项

OptionPurposeWhen to Enable
noUncheckedIndexedAccess
Forces null checks on array/object accessAlways for safety
exactOptionalPropertyTypes
Distinguishes
undefined
from missing
APIs with optional fields
verbatimModuleSyntax
Enforces explicit type-only importsESM projects
erasableSyntaxOnly
Node.js 22+ native TS supportType stripping environments
选项用途启用时机
noUncheckedIndexedAccess
强制对数组/对象访问进行空值检查为了安全始终启用
exactOptionalPropertyTypes
区分
undefined
与缺失属性
带有可选字段的API
verbatimModuleSyntax
强制执行显式类型仅导入ESM项目
erasableSyntaxOnly
Node.js 22+原生TS支持类型剥离环境

Local Baselines

本地基准配置

See
references/configuration.md
for repo-specific tsconfig patterns (CommonJS CLI, NodeNext strict, Next.js bundler).
查看
references/configuration.md
获取仓库专属的tsconfig模式(CommonJS CLI、NodeNext严格模式、Next.js打包器)。

Core 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

快速对比

LibraryBundle SizeSpeedBest For
Zod~13.5kBBaselineFull-stack apps, tRPC integration
TypeBox~8kB~10x fasterOpenAPI, performance-critical
Valibot~1.4kB~2x fasterEdge 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
type
vs
interface
?
  • Public API / library types →
    interface
  • Union types / mapped types →
    type
  • Simple object shapes →
    interface
    (default)
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) →
    unknown
    (type-safe)
  • Rapid prototyping / migration →
    any
    (temporarily)
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
需要在
type
interface
之间选择?
  • 公共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
incremental
, use
skipLibCheck
, consider esbuild/swc
→ See troubleshooting.md for detailed solutions with examples
属性在类型上不存在 → 定义正确的接口或使用可选属性
类型不可分配 → 修复属性类型或使用运行时验证(Zod)
对象可能为'undefined' → 使用可选链(
?.
)或类型守卫
无法找到模块 → 检查文件扩展名(ESM使用.js)与模块解析配置
编译缓慢 → 启用
incremental
,使用
skipLibCheck
,考虑esbuild/swc
→ 查看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:
    using
    keyword, stable decorators, import type behavior, satisfies with generics. Load when using modern language features.
  • 🌳 Decision Trees - Clear decision frameworks for
    type
    vs
    interface
    , generics vs unions,
    unknown
    vs
    any
    , validation library selection, type narrowing strategies, and module resolution. Load when making TypeScript design decisions.
  • 🔧 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+特性:
    using
    关键字、稳定装饰器、导入类型行为、带泛型的satisfies。使用现代语言特性时查看。
  • 🌳 决策树 - 清晰的决策框架,涵盖
    type
    vs
    interface
    、泛型vs联合类型、
    unknown
    vs
    any
    、验证库选择、类型收窄策略与模块解析。做TypeScript设计决策时查看。
  • 🔧 故障排除 - 常见TypeScript错误与修复、类型推断问题、模块解析问题、tsconfig配置错误、构建性能优化与类型兼容性错误。调试TypeScript问题时查看。

Red Flags

警示信号

Stop and reconsider if:
  • Using
    any
    instead of
    unknown
    for external data
  • Casting with
    as
    without runtime validation
  • Disabling strict mode for convenience
  • Using
    @ts-ignore
    without clear justification
  • Index access without
    noUncheckedIndexedAccess
若出现以下情况请停止并重新考虑:
  • 对外部数据使用
    any
    而非
    unknown
  • 未进行运行时验证就使用
    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类型
[若在你的技能包中部署了这些技能,可查看完整文档]