Skip to content

类型 Annotation

一句话解释

类型 annotation 是 explicit declaration 的变量's or 参数's 类型 using colon followed 通过类型 name.

用大白话说

类型 annotation tells TypeScript 什么类型值 应该是. 你编写它 之后 colon: let x: number = 5. The annotation is a compile-time hint — it is removed when the code is compiled to JavaScript.

Type annotations are optional in many cases because TypeScript can infer types automatically. However, explicit annotations are useful for function parameters (where inference is not possible), for making code more readable, and for catching errors where the wrong type is assigned.

Annotations are especially important for function parameters, since TypeScript cannot infer parameter types from usage. They are also helpful for public APIs where you want to be explicit about the expected types.

示例

typescript
let age: number = 25;
let name: string = "Bob";
let isActive: boolean = true;

function greet(person: string): string {
  return `Hello, ${person}`;
}

每个变量 and 函数参数有 explicit 类型 annotation 之后 colon.

常见混淆

  • 容易混淆的对象: 类型 assertion

    关键区别: annotation declares 类型 on 新变量; assertion overrides 类型的 existing 值 using 'as'.

相关术语

解读错误信息

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

查看错误

← 返回术语表