Skip to content

类型 Annotations and Inference

如何 编写 explicit 类型 annotations and 当到 rely on TypeScript's 类型 inference.

你将学到

  • 如何 编写 explicit 类型 annotations 使用 colon 语法
  • 当 TypeScript infers 类型 automatically
  • 为什么 explicit annotations matter for 函数 signatures
  • difference 之间 annotation and assertion

概念讲解

Explicit Annotations

A type annotation uses a colon to declare a variable's type: let 数量: 数字 = 0 or 函数 greet(name: 字符串): 字符串. Annotations are optional in many cases but valuable for function parameters (which have no inference context) and return types on public APIs. Explicit annotations serve as documentation and catch mistakes when a refactor changes the inferred type.

Type Inference

TypeScript can infer types without annotations. If you write let count = 0, TypeScript infers number. If you write const greeting = "hi", it infers the literal type "hi". Inference is powerful — you should let it work for local variables and only annotate where it adds clarity or safety. Over-annotating makes code verbose without adding value.

Annotations vs Assertions

An annotation (let x: 字符串 = y) checks that y is assignable to 字符串. A type assertion (let x = y as 字符串) tells the compiler "trust me, 这个是字符串" without checking. Assertions bypass the compiler's safety and should be used sparingly — typically when you know more than the compiler, like parsing unknown data from an API.

示例代码

              // Explicit annotation — the compiler verifies the value matches.
let itemCount: number = 42;
let label: string = "Products";

// Inference — TypeScript figures out the type automatically.
let total = 100;        // inferred as number
let message = "Hello";  // inferred as string
let items = [1, 2, 3];  // inferred as number[]

// Function parameters NEED annotations (no inference context).
function calculateTotal(price: number, qty: number): number {
  return price * qty;
}

// Type assertion — use sparingly, it bypasses checking.
let data: unknown = "12345";
let length = (data as string).length;
            

Annotate 函数参数 and 公共返回类型. Let inference handle 局部变量. Use assertions (as) 仅当 你 truly know better than 编译器.

动手试一试

  • JSON 到 TypeScript

    See 如何 inferred shapes become explicit annotations.

  • Code Diff

    Compare annotated and inferred versions 的相同 code.

常见错误

错误写法

Using 类型 assertions (as) 相反的 annotations 到 fix 错误

正确做法

Assertions silence 编译器不使用检查. Use 它们仅 for genuinely unknown 数据. Prefer proper annotations or 类型 guards.

错误写法

Annotating 每个局部变量当 inference 会工作

正确做法

Let TypeScript infer 类型 for 简单局部变量. Annotate 函数 signatures, 公共 APIs, and 位置哪里 inferred 类型是 也 broad.

练习 类型 Annotations and Inference

10 个练习

练习 类型 Annotations and Inference

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误