typescript

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

TypeScript

TypeScript

Overview

概述

TypeScript is JavaScript with static typing. It adds a compile-time type checker; runtime behavior is JavaScript. Learning JavaScript applies to TypeScript for runtime tasks (e.g. sorting a list, DOM, async). Use TypeScript for types, interfaces, generics, and better tooling.
Core idea: Types describe shape and contracts; the compiler catches type errors before run time. Enable
strict
in
tsconfig.json
as a best practice.

TypeScript是带有静态类型的JavaScript。它添加了一个编译时类型检查器;运行时行为与JavaScript一致。JavaScript的相关知识可直接应用于TypeScript的运行时任务(例如列表排序、DOM操作、异步处理)。使用TypeScript来实现类型定义、接口、泛型,并获得更优质的工具支持。
核心思想:类型用于描述数据的形状和契约;编译器会在运行前捕获类型错误。最佳实践是在
tsconfig.json
中启用
strict
模式。

Quick reference

快速参考

ConceptSyntax / note
Type annotation
let x: string
,
function f(n: number): void
Interface
interface User { name: string; id: number }
Type alias
type Id = string | number
Union
string
or
number
(union types)
Optional
prop?: string
or
prop: string | undefined
Generics
function id<T>(x: T): T { return x }
Infer type from schemaUse library (e.g. Zod:
z.infer<typeof schema>
)

概念语法 / 说明
类型注解
let x: string
,
function f(n: number): void
接口
interface User { name: string; id: number }
类型别名
type Id = string | number
联合类型
string
number
(联合类型)
可选属性
prop?: string
prop: string | undefined
泛型
function id<T>(x: T): T { return x }
从Schema推断类型使用库(例如Zod:
z.infer<typeof schema>

Everyday types

日常常用类型

  • Primitives:
    string
    ,
    number
    ,
    boolean
    ,
    bigint
    ,
    symbol
    .
  • Arrays:
    number[]
    or
    Array<number>
    .
  • Any:
    any
    — disables checking; avoid when possible. Prefer
    unknown
    for truly unknown data and narrow before use.
  • Type annotations (postfix):
    const name: string = "x"
    ,
    function greet(name: string): string { return "Hi " + name }
    .
  • Object types:
    { name: string; age?: number }
    or
    interface User { name: string; age?: number }
    .
  • Unions:
    string | number
    ; literal types:
    "a" | "b"
    .

  • 原始类型
    string
    ,
    number
    ,
    boolean
    ,
    bigint
    ,
    symbol
  • 数组
    number[]
    Array<number>
  • Any类型
    any
    —— 会禁用类型检查;尽可能避免使用。对于真正未知的数据,优先使用
    unknown
    类型,并在使用前进行类型收窄。
  • 类型注解(后缀式):
    const name: string = "x"
    ,
    function greet(name: string): string { return "Hi " + name }
  • 对象类型
    { name: string; age?: number }
    interface User { name: string; age?: number }
  • 联合类型
    string | number
    字面量类型
    "a" | "b"

Narrowing

类型收窄

Narrow types with conditionals so TypeScript can infer:
  • typeof:
    if (typeof x === "string") { ... }
  • Truthiness:
    if (value) { ... }
  • Equality:
    if (x === null) { ... }
  • in:
    if ("name" in obj) { ... }
  • Type guards:
    function isFish(pet: Fish | Bird): pet is Fish { ... }
  • Discriminated unions: Use a common literal field (e.g.
    kind: "circle"
    ) and switch on it.

通过条件语句收窄类型,让TypeScript能够进行推断:
  • typeof
    if (typeof x === "string") { ... }
  • 真值检查
    if (value) { ... }
  • 相等性检查
    if (x === null) { ... }
  • in操作符
    if ("name" in obj) { ... }
  • 类型守卫
    function isFish(pet: Fish | Bird): pet is Fish { ... }
  • 可辨识联合类型:使用一个公共的字面量字段(例如
    kind: "circle"
    )并基于它进行switch判断。

Functions

函数

  • Signatures:
    (a: string, b?: number) => boolean
    ; void for no return value.
  • Overloads: Multiple call signatures + one implementation.
  • Generics:
    function first<T>(arr: T[]): T \| undefined
    .
  • Constraints:
    function longest<T extends { length: number }>(a: T, b: T): T
    .

  • 签名
    (a: string, b?: number) => boolean
    void类型用于无返回值的函数。
  • 重载:多个调用签名 + 一个实现。
  • 泛型
    function first<T>(arr: T[]): T \| undefined
  • 约束
    function longest<T extends { length: number }>(a: T, b: T): T

Object types & type manipulation

对象类型与类型操作

  • Interfaces:
    interface Point { x: number; y: number }
    ;
    extends
    for extension.
  • Index signatures:
    [key: string]: number
    .
  • keyof:
    type K = keyof User
    → union of keys.
  • typeof:
    type C = typeof config
    (value → type).
  • Indexed access:
    type Name = User["name"]
    .
  • Mapped types:
    type Readonly<T> = { readonly [K in keyof T]: T[K] }
    .
  • Conditional types:
    type F = T extends string ? number : boolean
    .
  • Template literal types:
    type E = `on${Capitalize<Event>}`
    .
  • Utility types:
    Partial<T>
    ,
    Required<T>
    ,
    Pick<T, K>
    ,
    Omit<T, K>
    ,
    Record<K, V>
    ,
    Exclude<T, U>
    ,
    Extract<T, U>
    ,
    NonNullable<T>
    ,
    ReturnType<F>
    ,
    Parameters<F>
    .

  • 接口
    interface Point { x: number; y: number }
    ;使用
    extends
    进行扩展。
  • 索引签名
    [key: string]: number
  • keyof操作符
    type K = keyof User
    → 键的联合类型。
  • typeof操作符
    type C = typeof config
    (从值生成类型)。
  • 索引访问
    type Name = User["name"]
  • 映射类型
    type Readonly<T> = { readonly [K in keyof T]: T[K] }
  • 条件类型
    type F = T extends string ? number : boolean
  • 模板字面量类型
    type E = `on${Capitalize<Event>}`
  • 工具类型
    Partial<T>
    ,
    Required<T>
    ,
    Pick<T, K>
    ,
    Omit<T, K>
    ,
    Record<K, V>
    ,
    Exclude<T, U>
    ,
    Extract<T, U>
    ,
    NonNullable<T>
    ,
    ReturnType<F>
    ,
    Parameters<F>

Classes

  • Members:
    class C { prop: number; method(): void {} }
    .
  • Constructor:
    constructor(public name: string) {}
    (parameter property).
  • Implements:
    class D implements I {}
    .
  • Extends:
    class Child extends Parent {}
    .
  • Readonly, private, protected as needed.

  • 成员
    class C { prop: number; method(): void {} }
  • 构造函数
    constructor(public name: string) {}
    (参数属性)。
  • 实现接口
    class D implements I {}
  • 继承
    class Child extends Parent {}
  • 根据需要使用Readonlyprivateprotected修饰符。

Modules

模块

  • ES modules:
    import { x } from "./file"
    ,
    export const x = 1
    ,
    export type { T }
    .
  • Default export:
    export default App
    ,
    import App from "./App"
    .
  • Namespace (legacy): Prefer ES modules.

  • ES模块
    import { x } from "./file"
    ,
    export const x = 1
    ,
    export type { T }
  • 默认导出
    export default App
    ,
    import App from "./App"
  • 命名空间(遗留方案):优先使用ES模块。

Project configuration: tsconfig.json

项目配置:tsconfig.json

  • strict: Set
    "strict": true
    (recommended). Enables strictNullChecks, noImplicitAny, strictFunctionTypes, etc.
  • target: e.g.
    "ES2022"
    or
    "ESNext"
    .
  • module: e.g.
    "ESNext"
    ,
    "NodeNext"
    for Node.
  • moduleResolution:
    "bundler"
    (with bundler),
    "NodeNext"
    for Node.
  • paths:
    "@/*": ["./src/*"]
    for path aliases.
  • include / exclude: Which files are compiled.
  • References: Use project references for large monorepos.
See reference.md for official TSConfig Reference link.

  • strict:设置
    "strict": true
    (推荐)。会启用strictNullChecks、noImplicitAny、strictFunctionTypes等严格检查选项。
  • target:例如
    "ES2022"
    "ESNext"
  • module:例如
    "ESNext"
    ,Node环境下使用
    "NodeNext"
  • moduleResolution:使用打包工具时选
    "bundler"
    ,Node环境下选
    "NodeNext"
  • paths
    "@/*": ["./src/*"]
    用于路径别名配置。
  • include / exclude:指定哪些文件需要被编译。
  • References:在大型单体仓库中使用项目引用。
查看reference.md获取官方TSConfig参考链接。

Best practices

最佳实践

  • Enable strict mode.
  • Prefer interfaces for object shapes that may be extended; type for unions, mapped types, and aliases.
  • Prefer const and readonly where possible.
  • Use unknown instead of any for external data; narrow before use.
  • Use generics to keep functions reusable and type-safe.
  • For runtime validation + types, use a schema library (e.g. Zod) and infer types with
    z.infer<typeof schema>
    .

  • 启用strict模式。
  • 对于可能需要扩展的对象形状,优先使用interfaces;对于联合类型、映射类型和别名,优先使用type
  • 尽可能使用constreadonly
  • 对于外部数据,使用unknown而非any;在使用前进行类型收窄。
  • 使用泛型让函数保持可复用性和类型安全性。
  • 如需同时进行运行时验证和类型定义,使用Schema库(例如Zod)并通过
    z.infer<typeof schema>
    推断类型。

Common mistakes

常见错误

  • any: Avoid; use
    unknown
    and narrow, or proper types.
  • Non-null assertion (
    !
    )
    : Use sparingly; prefer narrowing or optional chaining.
  • Type assertions (
    as
    )
    : Prefer type guards or schema validation when data comes from outside.
  • Strict off: Keep
    strict: true
    ; fix errors rather than disabling.

  • any类型:避免使用;改用
    unknown
    并进行类型收窄,或使用正确的类型定义。
  • 非空断言(
    !
    :谨慎使用;优先选择类型收窄或可选链操作。
  • 类型断言(
    as
    :当数据来自外部时,优先使用类型守卫或Schema验证。
  • 关闭严格模式:保持
    strict: true
    ;修复错误而非禁用检查。

Additional resources

额外资源

  • reference.md — Official documentation links (Handbook, Reference, TSConfig, Cheat Sheets).
  • Official: https://www.typescriptlang.org/docs — Get Started, Handbook, Reference, TSConfig.
  • reference.md —— 官方文档链接(手册、参考、TSConfig、速查表)。
  • 官方网站https://www.typescriptlang.org/docs —— 入门指南、手册、参考、TSConfig配置。