Skip to content

类型 Assertion

一句话解释

类型 assertion (值 as 类型 or <类型>值) tells TypeScript 到 treat 值 as 不同类型. 它是 编译-时间提示使用否 运行时副作用.

用大白话说

类型 assertion overrides TypeScript's inferred 类型. 你编写 value as Type to tell the compiler "trust me, 这个值是的类型类型." It is a compile-time operation — no runtime check is performed.

Type assertions are useful when you know more than TypeScript does, e.g., parsing JSON or working with DOM elements. However, they bypass type safety — if the assertion is wrong, you get a runtime error.

Prefer type narrowing (typeof, instanceof, type guards) over assertions when possible. Use unknown instead of 任何 for values where you need to assert, as it forces you to narrow before use.

示例

typescript
const value: unknown = JSON.parse('{"name":"Alice"}');
const obj = value as { name: string };
console.log(obj.name); // "Alice"

// DOM example
const input = document.getElementById("email") as HTMLInputElement;
console.log(input.value);

Assertions tell TypeScript 类型不使用运行时检查. Use sparingly.

常见混淆

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

    关键区别: Assertions override existing 类型; annotations declare 类型 on 新变量. Assertions 能是 unsafe; annotations 是总是 safe.

相关术语

解读错误信息

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

查看错误

← 返回术语表