typescript
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTypeScript
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 in as a best practice.
stricttsconfig.jsonTypeScript是带有静态类型的JavaScript。它添加了一个编译时类型检查器;运行时行为与JavaScript一致。JavaScript的相关知识可直接应用于TypeScript的运行时任务(例如列表排序、DOM操作、异步处理)。使用TypeScript来实现类型定义、接口、泛型,并获得更优质的工具支持。
核心思想:类型用于描述数据的形状和契约;编译器会在运行前捕获类型错误。最佳实践是在中启用模式。
tsconfig.jsonstrictQuick reference
快速参考
| Concept | Syntax / note |
|---|---|
| Type annotation | |
| Interface | |
| Type alias | |
| Union | |
| Optional | |
| Generics | |
| Infer type from schema | Use library (e.g. Zod: |
| 概念 | 语法 / 说明 |
|---|---|
| 类型注解 | |
| 接口 | |
| 类型别名 | |
| 联合类型 | |
| 可选属性 | |
| 泛型 | |
| 从Schema推断类型 | 使用库(例如Zod: |
Everyday types
日常常用类型
- Primitives: ,
string,number,boolean,bigint.symbol - Arrays: or
number[].Array<number> - Any: — disables checking; avoid when possible. Prefer
anyfor truly unknown data and narrow before use.unknown - Type annotations (postfix): ,
const name: string = "x".function greet(name: string): string { return "Hi " + name } - Object types: or
{ name: string; age?: number }.interface User { name: string; age?: number } - Unions: ; literal types:
string | number."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. ) and switch on it.
kind: "circle"
通过条件语句收窄类型,让TypeScript能够进行推断:
- typeof:
if (typeof x === "string") { ... } - 真值检查:
if (value) { ... } - 相等性检查:
if (x === null) { ... } - in操作符:
if ("name" in obj) { ... } - 类型守卫:
function isFish(pet: Fish | Bird): pet is Fish { ... } - 可辨识联合类型:使用一个公共的字面量字段(例如)并基于它进行switch判断。
kind: "circle"
Functions
函数
- Signatures: ; void for no return value.
(a: string, b?: number) => boolean - 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
- 签名:;void类型用于无返回值的函数。
(a: string, b?: number) => boolean - 重载:多个调用签名 + 一个实现。
- 泛型:。
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 }for extension.extends - Index signatures: .
[key: string]: number - keyof: → union of keys.
type K = keyof User - typeof: (value → type).
type C = typeof config - 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: (parameter property).
constructor(public name: string) {} - 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 {} - 根据需要使用Readonly、private、protected修饰符。
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 (recommended). Enables strictNullChecks, noImplicitAny, strictFunctionTypes, etc.
"strict": true - target: e.g. or
"ES2022"."ESNext" - module: e.g. ,
"ESNext"for Node."NodeNext" - moduleResolution: (with bundler),
"bundler"for Node."NodeNext" - paths: for path aliases.
"@/*": ["./src/*"] - include / exclude: Which files are compiled.
- References: Use project references for large monorepos.
See reference.md for official TSConfig Reference link.
- strict:设置(推荐)。会启用strictNullChecks、noImplicitAny、strictFunctionTypes等严格检查选项。
"strict": true - target:例如或
"ES2022"。"ESNext" - module:例如,Node环境下使用
"ESNext"。"NodeNext" - moduleResolution:使用打包工具时选,Node环境下选
"bundler"。"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。
- 尽可能使用const和readonly。
- 对于外部数据,使用unknown而非any;在使用前进行类型收窄。
- 使用泛型让函数保持可复用性和类型安全性。
- 如需同时进行运行时验证和类型定义,使用Schema库(例如Zod)并通过推断类型。
z.infer<typeof schema>
Common mistakes
常见错误
- any: Avoid; use and narrow, or proper types.
unknown - Non-null assertion (): Use sparingly; prefer narrowing or optional chaining.
! - Type assertions (): Prefer type guards or schema validation when data comes from outside.
as - Strict off: Keep ; fix errors rather than disabling.
strict: true
- any类型:避免使用;改用并进行类型收窄,或使用正确的类型定义。
unknown - 非空断言():谨慎使用;优先选择类型收窄或可选链操作。
! - 类型断言():当数据来自外部时,优先使用类型守卫或Schema验证。
as - 关闭严格模式:保持;修复错误而非禁用检查。
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配置。