typescript
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTypeScript
TypeScript
Overview
概述
TypeScript is a statically typed superset of JavaScript that compiles to plain JavaScript. It adds optional type annotations, interfaces, generics, and advanced type-level programming to JavaScript, enabling safer refactoring, better tooling, and self-documenting code. TypeScript has become the default choice for professional JavaScript development across frontend frameworks, backend services, CLIs, and serverless functions.
TypeScript是JavaScript的静态类型超集,可编译为普通JavaScript代码。它为JavaScript添加了可选类型注解、接口、泛型和高级类型级编程能力,使代码重构更安全、工具链更完善,同时具备自文档化特性。如今,TypeScript已成为前端框架、后端服务、CLI工具和无服务器函数等专业JavaScript开发的默认选择。
Knowledge Map
知识图谱
typescript/
├── project-system/ # tsconfig.json, build tools, bundlers, compilation
├── package-management/ # npm, yarn, pnpm, bun, workspaces, publishing
├── cli/ # Commander, yargs, oclif, ink, chalk, CLI tooling
└── packages/ # Popular libraries (Express, Next.js, Zod, Prisma, etc.)typescript/
├── project-system/ # tsconfig.json, build tools, bundlers, compilation
├── package-management/ # npm, yarn, pnpm, bun, workspaces, publishing
├── cli/ # Commander, yargs, oclif, ink, chalk, CLI tooling
└── packages/ # Popular libraries (Express, Next.js, Zod, Prisma, etc.)Choosing Guide
选择指南
| Problem | Sub-Skill | Notes |
|---|---|---|
| Configure tsconfig.json or compiler options | | Covers target, module, strict, paths, and all compiler flags |
| Choose or configure a bundler (Vite, esbuild, etc.) | | Build tool comparison with speed, features, and config examples |
| Set up monorepo with project references | | Composite projects, tsc --build, path aliases |
| Choose a package manager (npm, pnpm, yarn, bun) | | Feature comparison, lockfiles, disk usage, monorepo support |
| Configure workspaces for a monorepo | | npm/yarn/pnpm/bun workspace patterns and turborepo integration |
| Publish a package to npm | | Publishing workflow, provenance, package.json exports |
| Build a CLI tool | | Commander, yargs, oclif, ink for TUI, packaging strategies |
| Add interactive prompts or terminal styling | | inquirer, prompts, chalk, ora, listr2 |
| Choose or use a specific library | | Express, Fastify, Next.js, Zod, Prisma, tRPC, and more |
| 问题 | 子技能 | 说明 |
|---|---|---|
| 配置tsconfig.json或编译器选项 | | 涵盖target、module、strict、paths及所有编译器标志 |
| 选择或配置打包器(Vite、esbuild等) | | 构建工具对比,包括速度、特性和配置示例 |
| 使用项目引用搭建单仓库(monorepo) | | 复合项目、tsc --build、路径别名 |
| 选择包管理器(npm、pnpm、yarn、bun) | | 特性对比、锁文件、磁盘占用、单仓库支持 |
| 为单仓库配置工作区 | | npm/yarn/pnpm/bun工作区模式及turborepo集成 |
| 发布包到npm | | 发布流程、来源验证、package.json exports配置 |
| 构建CLI工具 | | Commander、yargs、oclif、ink(用于TUI)、打包策略 |
| 添加交互式提示或终端样式 | | inquirer、prompts、chalk、ora、listr2 |
| 选择或使用特定库 | | Express、Fastify、Next.js、Zod、Prisma、tRPC等 |
TypeScript Version Landscape
TypeScript版本景观
| Version | Key Features |
|---|---|
| 4.0 | Variadic tuple types, labeled tuple elements, class property inference from constructors |
| 4.1 | Template literal types, key remapping in mapped types, recursive conditional types |
| 4.2 | Leading/middle rest elements in tuples, stricter |
| 4.3 | |
| 4.4 | Control flow analysis of aliased conditions, symbol and template literal index signatures |
| 4.5 | |
| 4.6 | Control flow analysis for destructured discriminated unions, |
| 4.7 | |
| 4.8 | Improved intersection reduction, |
| 4.9 | |
| 5.0 | Decorators (TC39 standard), |
| 5.1 | Easier implicit returns for |
| 5.2 | |
| 5.3 | Import attributes, |
| 5.4 | |
| 5.5+ | Inferred type predicates, |
| 版本 | 核心特性 |
|---|---|
| 4.0 | 可变元组类型、带标签的元组元素、从构造函数推断类属性类型 |
| 4.1 | 模板字面量类型、映射类型中的键重映射、递归条件类型 |
| 4.2 | 元组中的开头/中间剩余元素、更严格的 |
| 4.3 | |
| 4.4 | 别名条件的控制流分析、符号和模板字面量索引签名 |
| 4.5 | |
| 4.6 | 解构判别联合的控制流分析、 |
| 4.7 | |
| 4.8 | 改进的交集归约、 |
| 4.9 | |
| 5.0 | 装饰器(TC39标准)、 |
| 5.1 | |
| 5.2 | |
| 5.3 | 导入属性、 |
| 5.4 | |
| 5.5+ | 推断类型谓词、 |
Core Language Features Quick Reference
核心语言特性速查
Type System Fundamentals
类型系统基础
typescript
// Union types — value can be one of several types
type Result = "success" | "error" | "pending";
type ID = string | number;
// Intersection types — combine multiple types
type Employee = Person & { employeeId: string };
// Generics — parameterized types
function first<T>(arr: T[]): T | undefined {
return arr[0];
}
// Conditional types — type-level if/else
type IsString<T> = T extends string ? true : false;
// Mapped types — transform properties
type Readonly<T> = { readonly [K in keyof T]: T[K] };
type Optional<T> = { [K in keyof T]?: T[K] };
// Template literal types — string manipulation at the type level
type EventName<T extends string> = `on${Capitalize<T>}`;
type ClickEvent = EventName<"click">; // "onClick"
// satisfies operator — validate type without widening
const palette = {
red: [255, 0, 0],
green: "#00ff00",
} satisfies Record<string, string | number[]>;
// const assertions — narrow to literal types
const routes = ["home", "about", "contact"] as const;
type Route = (typeof routes)[number]; // "home" | "about" | "contact"
// Discriminated unions — tagged union pattern
type Shape =
| { kind: "circle"; radius: number }
| { kind: "rectangle"; width: number; height: number };
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "rectangle":
return shape.width * shape.height;
}
}typescript
// Union types — value can be one of several types
type Result = "success" | "error" | "pending";
type ID = string | number;
// Intersection types — combine multiple types
type Employee = Person & { employeeId: string };
// Generics — parameterized types
function first<T>(arr: T[]): T | undefined {
return arr[0];
}
// Conditional types — type-level if/else
type IsString<T> = T extends string ? true : false;
// Mapped types — transform properties
type Readonly<T> = { readonly [K in keyof T]: T[K] };
type Optional<T> = { [K in keyof T]?: T[K] };
// Template literal types — string manipulation at the type level
type EventName<T extends string> = `on${Capitalize<T>}`;
type ClickEvent = EventName<"click">; // "onClick"
// satisfies operator — validate type without widening
const palette = {
red: [255, 0, 0],
green: "#00ff00",
} satisfies Record<string, string | number[]>;
// const assertions — narrow to literal types
const routes = ["home", "about", "contact"] as const;
type Route = (typeof routes)[number]; // "home" | "about" | "contact"
// Discriminated unions — tagged union pattern
type Shape =
| { kind: "circle"; radius: number }
| { kind: "rectangle"; width: number; height: number };
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "rectangle":
return shape.width * shape.height;
}
}Key Utility Types
核心工具类型
| Utility | Purpose | Example |
|---|---|---|
| Make all properties optional | |
| Make all properties required | |
| Make all properties readonly | |
| Select specific properties | |
| Remove specific properties | |
| Object type with key/value types | |
| Remove types from a union | |
| Keep only matching union members | |
| Remove null and undefined | |
| Extract function return type | |
| Extract function parameter types | |
| Unwrap Promise types | |
| Prevent inference on a type parameter | |
| 工具类型 | 用途 | 示例 |
|---|---|---|
| 将所有属性设为可选 | |
| 将所有属性设为必填 | |
| 将所有属性设为只读 | |
| 选择特定属性 | |
| 移除特定属性 | |
| 带键/值类型的对象类型 | |
| 从联合类型中移除指定类型 | |
| 仅保留联合类型中匹配的成员 | |
| 移除null和undefined | |
| 提取函数返回类型 | |
| 提取函数参数类型 | |
| 解包Promise类型 | |
| 阻止类型参数的推断 | 默认参数中的 |
Runtime Options
运行时选项
| Runtime | Key Strengths | TypeScript Support |
|---|---|---|
| Node.js | Largest ecosystem, widest deployment, mature tooling | Via |
| Deno | Built-in TypeScript, secure by default, web-standard APIs | Native — no build step required |
| Bun | Fastest startup, built-in bundler/test runner/package manager | Native — runs |
| Cloudflare Workers | Edge computing, V8 isolates, global deployment | Via Wrangler with esbuild under the hood |
| 运行时 | 核心优势 | TypeScript支持 |
|---|---|---|
| Node.js | 生态系统最庞大、部署范围最广、工具链成熟 | 通过 |
| Deno | 内置TypeScript、默认安全、Web标准API | 原生支持——无需构建步骤 |
| Bun | 启动速度最快、内置打包器/测试运行器/包管理器 | 原生支持——直接运行 |
| Cloudflare Workers | 边缘计算、V8隔离、全球部署 | 通过Wrangler支持,底层基于esbuild |
Choosing a Runtime
运行时选择指南
- Building a production server or API? Node.js has the broadest library support and hosting options.
- Want built-in TypeScript with no config? Deno runs natively with LSP and formatter included.
.ts - Need maximum startup speed or an all-in-one tool? Bun combines runtime, bundler, package manager, and test runner.
- Deploying at the edge? Cloudflare Workers provide sub-millisecond cold starts globally.
- 构建生产服务器或API? Node.js拥有最广泛的库支持和托管选项。
- 想要内置TypeScript且无需配置? Deno原生运行文件,包含LSP和格式化工具。
.ts - 需要极致启动速度或一体化工具? Bun整合了运行时、打包器、包管理器和测试运行器。
- 部署到边缘? Cloudflare Workers提供全球范围内的亚毫秒级冷启动。
Best Practices
最佳实践
-
Enablemode in every project. It enables
strict,strictNullChecks,noImplicitAny, and other flags that catch real bugs.strictFunctionTypes -
Avoid— it disables all type checking. Use
anywhen the type is truly unknown, then narrow with type guards.unknown -
Preferover
unknownfor values of uncertain type:anytypescriptfunction parse(input: unknown): Config { if (typeof input === "object" && input !== null && "port" in input) { return input as Config; } throw new Error("Invalid config"); } -
Use type narrowing instead of type assertions:typescript
// Prefer this if (typeof value === "string") { console.log(value.toUpperCase()); } // Over this console.log((value as string).toUpperCase()); -
Use branded types for domain identifiers to prevent mixing:typescript
type UserId = string & { __brand: "UserId" }; type OrderId = string & { __brand: "OrderId" }; function getUser(id: UserId): User { /* ... */ } // getUser(orderId) — compile error! -
Useto validate object shapes without widening types.
satisfies -
Useassertions for literal tuples and objects that should not be widened.
const -
Use discriminated unions for state machines and variant types instead of optional properties.
-
Enableto force undefined checks on dynamic property access.
noUncheckedIndexedAccess -
Keepout of library boundaries — validate external data at the edge with Zod, io-ts, or similar runtime validators.
any
-
在所有项目中启用模式。它会启用
strict、strictNullChecks、noImplicitAny等标志,帮助捕获实际bug。strictFunctionTypes -
避免使用——它会禁用所有类型检查。当类型确实未知时,使用
any,然后通过类型守卫收窄类型。unknown -
**优先使用而非
unknown**处理类型不确定的值:anytypescriptfunction parse(input: unknown): Config { if (typeof input === "object" && input !== null && "port" in input) { return input as Config; } throw new Error("Invalid config"); } -
使用类型收窄而非类型断言:typescript
// 推荐写法 if (typeof value === "string") { console.log(value.toUpperCase()); } // 不推荐写法 console.log((value as string).toUpperCase()); -
使用品牌类型处理领域标识符,避免混淆:typescript
type UserId = string & { __brand: "UserId" }; type OrderId = string & { __brand: "OrderId" }; function getUser(id: UserId): User { /* ... */ } // getUser(orderId) —— 编译错误! -
**使用**验证对象形状而不拓宽类型。
satisfies -
使用断言处理不应被拓宽的字面量元组和对象。
const -
使用判别联合处理状态机和变体类型,而非可选属性。
-
**启用**强制对动态属性访问进行undefined检查。
noUncheckedIndexedAccess -
在库边界避免——在边缘层使用Zod、io-ts或类似的运行时验证器验证外部数据。
any