typescript

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

TypeScript

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

选择指南

ProblemSub-SkillNotes
Configure tsconfig.json or compiler options
project-system
Covers target, module, strict, paths, and all compiler flags
Choose or configure a bundler (Vite, esbuild, etc.)
project-system
Build tool comparison with speed, features, and config examples
Set up monorepo with project references
project-system
Composite projects, tsc --build, path aliases
Choose a package manager (npm, pnpm, yarn, bun)
package-management
Feature comparison, lockfiles, disk usage, monorepo support
Configure workspaces for a monorepo
package-management
npm/yarn/pnpm/bun workspace patterns and turborepo integration
Publish a package to npm
package-management
Publishing workflow, provenance, package.json exports
Build a CLI tool
cli
Commander, yargs, oclif, ink for TUI, packaging strategies
Add interactive prompts or terminal styling
cli
inquirer, prompts, chalk, ora, listr2
Choose or use a specific library
packages
Express, Fastify, Next.js, Zod, Prisma, tRPC, and more
问题子技能说明
配置tsconfig.json或编译器选项
project-system
涵盖target、module、strict、paths及所有编译器标志
选择或配置打包器(Vite、esbuild等)
project-system
构建工具对比,包括速度、特性和配置示例
使用项目引用搭建单仓库(monorepo)
project-system
复合项目、tsc --build、路径别名
选择包管理器(npm、pnpm、yarn、bun)
package-management
特性对比、锁文件、磁盘占用、单仓库支持
为单仓库配置工作区
package-management
npm/yarn/pnpm/bun工作区模式及turborepo集成
发布包到npm
package-management
发布流程、来源验证、package.json exports配置
构建CLI工具
cli
Commander、yargs、oclif、ink(用于TUI)、打包策略
添加交互式提示或终端样式
cli
inquirer、prompts、chalk、ora、listr2
选择或使用特定库
packages
Express、Fastify、Next.js、Zod、Prisma、tRPC等

TypeScript Version Landscape

TypeScript版本景观

VersionKey Features
4.0Variadic tuple types, labeled tuple elements, class property inference from constructors
4.1Template literal types, key remapping in mapped types, recursive conditional types
4.2Leading/middle rest elements in tuples, stricter
in
operator checks
4.3
override
keyword, template literal type improvements,
static
index signatures
4.4Control flow analysis of aliased conditions, symbol and template literal index signatures
4.5
Awaited
type, tail-recursive conditional types,
type
modifiers on import names
4.6Control flow analysis for destructured discriminated unions,
--target es2022
4.7
extends
constraints on
infer
, instantiation expressions,
moduleSuffixes
4.8Improved intersection reduction,
--build
mode
--watch
, template literal narrowing
4.9
satisfies
operator,
in
narrowing for unlisted properties, auto-accessors
5.0Decorators (TC39 standard),
const
type parameters,
--moduleResolution bundler
5.1Easier implicit returns for
undefined
, unrelated types for getters/setters,
@param
JSDoc linking
5.2
using
declarations (explicit resource management), decorator metadata
5.3Import attributes,
--resolution-mode
in
/// <reference>
, narrowing in
switch (true)
5.4
NoInfer
utility type, preserved narrowing in closures,
Object.groupBy
/
Map.groupBy
5.5+Inferred type predicates,
isolatedDeclarations
, regex syntax checking
版本核心特性
4.0可变元组类型、带标签的元组元素、从构造函数推断类属性类型
4.1模板字面量类型、映射类型中的键重映射、递归条件类型
4.2元组中的开头/中间剩余元素、更严格的
in
运算符检查
4.3
override
关键字、模板字面量类型优化、
static
索引签名
4.4别名条件的控制流分析、符号和模板字面量索引签名
4.5
Awaited
类型、尾递归条件类型、导入名称的
type
修饰符
4.6解构判别联合的控制流分析、
--target es2022
4.7
infer
上的
extends
约束、实例化表达式、
moduleSuffixes
4.8改进的交集归约、
--build
模式下的
--watch
、模板字面量收窄
4.9
satisfies
运算符、未列出属性的
in
收窄、自动访问器
5.0装饰器(TC39标准)、
const
类型参数、
--moduleResolution bundler
5.1
undefined
的隐式返回更便捷、getter/setter的无关类型、
@param
JSDoc链接
5.2
using
声明(显式资源管理)、装饰器元数据
5.3导入属性、
/// <reference>
中的
--resolution-mode
switch (true)
中的类型收窄
5.4
NoInfer
工具类型、闭包中保留类型收窄、
Object.groupBy
/
Map.groupBy
5.5+推断类型谓词、
isolatedDeclarations
、正则语法检查

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

核心工具类型

UtilityPurposeExample
Partial<T>
Make all properties optional
Partial<User>
Required<T>
Make all properties required
Required<Config>
Readonly<T>
Make all properties readonly
Readonly<State>
Pick<T, K>
Select specific properties
Pick<User, "id" | "name">
Omit<T, K>
Remove specific properties
Omit<User, "password">
Record<K, V>
Object type with key/value types
Record<string, number>
Exclude<T, U>
Remove types from a union
Exclude<Status, "deleted">
Extract<T, U>
Keep only matching union members
Extract<Event, { type: "click" }>
NonNullable<T>
Remove null and undefined
NonNullable<string | null>
ReturnType<T>
Extract function return type
ReturnType<typeof fetch>
Parameters<T>
Extract function parameter types
Parameters<typeof setTimeout>
Awaited<T>
Unwrap Promise types
Awaited<Promise<string>>
NoInfer<T>
Prevent inference on a type parameter
NoInfer<T>
in default args
工具类型用途示例
Partial<T>
将所有属性设为可选
Partial<User>
Required<T>
将所有属性设为必填
Required<Config>
Readonly<T>
将所有属性设为只读
Readonly<State>
Pick<T, K>
选择特定属性
Pick<User, "id" | "name">
Omit<T, K>
移除特定属性
Omit<User, "password">
Record<K, V>
带键/值类型的对象类型
Record<string, number>
Exclude<T, U>
从联合类型中移除指定类型
Exclude<Status, "deleted">
Extract<T, U>
仅保留联合类型中匹配的成员
Extract<Event, { type: "click" }>
NonNullable<T>
移除null和undefined
NonNullable<string | null>
ReturnType<T>
提取函数返回类型
ReturnType<typeof fetch>
Parameters<T>
提取函数参数类型
Parameters<typeof setTimeout>
Awaited<T>
解包Promise类型
Awaited<Promise<string>>
NoInfer<T>
阻止类型参数的推断默认参数中的
NoInfer<T>

Runtime Options

运行时选项

RuntimeKey StrengthsTypeScript Support
Node.jsLargest ecosystem, widest deployment, mature toolingVia
tsc
,
ts-node
,
tsx
,
esbuild
, or
swc
DenoBuilt-in TypeScript, secure by default, web-standard APIsNative — no build step required
BunFastest startup, built-in bundler/test runner/package managerNative — runs
.ts
files directly
Cloudflare WorkersEdge computing, V8 isolates, global deploymentVia Wrangler with esbuild under the hood
运行时核心优势TypeScript支持
Node.js生态系统最庞大、部署范围最广、工具链成熟通过
tsc
ts-node
tsx
esbuild
swc
支持
Deno内置TypeScript、默认安全、Web标准API原生支持——无需构建步骤
Bun启动速度最快、内置打包器/测试运行器/包管理器原生支持——直接运行
.ts
文件
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
    .ts
    natively with LSP and formatter included.
  • 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原生运行
    .ts
    文件,包含LSP和格式化工具。
  • 需要极致启动速度或一体化工具? Bun整合了运行时、打包器、包管理器和测试运行器。
  • 部署到边缘? Cloudflare Workers提供全球范围内的亚毫秒级冷启动。

Best Practices

最佳实践

  1. Enable
    strict
    mode
    in every project. It enables
    strictNullChecks
    ,
    noImplicitAny
    ,
    strictFunctionTypes
    , and other flags that catch real bugs.
  2. Avoid
    any
    — it disables all type checking. Use
    unknown
    when the type is truly unknown, then narrow with type guards.
  3. Prefer
    unknown
    over
    any
    for values of uncertain type:
    typescript
    function parse(input: unknown): Config {
      if (typeof input === "object" && input !== null && "port" in input) {
        return input as Config;
      }
      throw new Error("Invalid config");
    }
  4. 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());
  5. 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!
  6. Use
    satisfies
    to validate object shapes without widening types.
  7. Use
    const
    assertions
    for literal tuples and objects that should not be widened.
  8. Use discriminated unions for state machines and variant types instead of optional properties.
  9. Enable
    noUncheckedIndexedAccess
    to force undefined checks on dynamic property access.
  10. Keep
    any
    out of library boundaries
    — validate external data at the edge with Zod, io-ts, or similar runtime validators.
  1. 在所有项目中启用
    strict
    模式
    。它会启用
    strictNullChecks
    noImplicitAny
    strictFunctionTypes
    等标志,帮助捕获实际bug。
  2. 避免使用
    any
    ——它会禁用所有类型检查。当类型确实未知时,使用
    unknown
    ,然后通过类型守卫收窄类型。
  3. **优先使用
    unknown
    而非
    any
    **处理类型不确定的值:
    typescript
    function parse(input: unknown): Config {
      if (typeof input === "object" && input !== null && "port" in input) {
        return input as Config;
      }
      throw new Error("Invalid config");
    }
  4. 使用类型收窄而非类型断言
    typescript
    // 推荐写法
    if (typeof value === "string") {
      console.log(value.toUpperCase());
    }
    // 不推荐写法
    console.log((value as string).toUpperCase());
  5. 使用品牌类型处理领域标识符,避免混淆:
    typescript
    type UserId = string & { __brand: "UserId" };
    type OrderId = string & { __brand: "OrderId" };
    
    function getUser(id: UserId): User { /* ... */ }
    // getUser(orderId) —— 编译错误!
  6. **使用
    satisfies
    **验证对象形状而不拓宽类型。
  7. 使用
    const
    断言
    处理不应被拓宽的字面量元组和对象。
  8. 使用判别联合处理状态机和变体类型,而非可选属性。
  9. **启用
    noUncheckedIndexedAccess
    **强制对动态属性访问进行undefined检查。
  10. 在库边界避免
    any
    ——在边缘层使用Zod、io-ts或类似的运行时验证器验证外部数据。