Skip to content

空 and undefined

一句话解释

空 and undefined 是 distinct 类型 in TypeScript. 使用 strictNullChecks 启用, 它们是 不 assignable 到 other 类型, preventing 空引用错误.

用大白话说

In TypeScript, null and undefined 是 separate 类型. 使用 strictNullChecks (部分的 strict 模式), 它们是 不 implicitly assignable 到 other 类型 — 你必须 explicitly 包含它们 in unions: string | null | undefined.

This prevents the most common runtime error: accessing a property on null or undefined. TypeScript forces you to check for null before using a value that might be null, using if checks, optional chaining (?.), or nullish coalescing (??).

Without strictNullChecks, 空 and undefined are assignable to any type, which defeats type safety. Always enable strict mode in new projects.

示例

typescript
let name: string | null = null;
// name.toUpperCase(); // Error: possibly null

if (name !== null) {
  name.toUpperCase(); // OK: narrowed to string
}

// Or use optional chaining
name?.toUpperCase(); // returns undefined if name is null

strictNullChecks forces 你到 handle 空之前 using 值.

相关术语

解读错误信息

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

查看错误

← 返回术语表