Glittering's blog Glittering's blog
Home
  • 学习手册

    • 《JavaScript教程》
    • 《TypeScript教程》
    • 《Git》
    • 《Vite》
    • 《Vue3》
    • 《React18》
    • 《CSS》
    • 《Tailwind CSS》
    • 《ES6 教程》
    • 《TypeScript 从零实现 axios》
  • 技术文档
  • 算法
  • 工作总结
  • 实用技巧
  • collect
About
  • Classification
  • Label
GitHub (opens new window)

Glitz Ma

前端开发工程师
Home
  • 学习手册

    • 《JavaScript教程》
    • 《TypeScript教程》
    • 《Git》
    • 《Vite》
    • 《Vue3》
    • 《React18》
    • 《CSS》
    • 《Tailwind CSS》
    • 《ES6 教程》
    • 《TypeScript 从零实现 axios》
  • 技术文档
  • 算法
  • 工作总结
  • 实用技巧
  • collect
About
  • Classification
  • Label
GitHub (opens new window)
  • 数据类型

    • 初识typescript及数据类型
    • 类
    • 接口
    • 泛型
    • 结构类型系统
    • 类型保护
    • 类型变换
    • 模块和命名空间
    • 类型声明
    • null和undefined
      • 一、null 和 undefined 在 TS 中是什么?
      • 二、关键前提:strictNullChecks
        • 开 / 关的本质区别
        • ❌ 未开启(老项目)
        • ✅ 开启(现代 TS 项目,默认)
      • 三、正确使用 null / undefined 的方式
        • 1️⃣ 显式声明可空
        • 2️⃣ 对象属性中的可选 vs undefined
        • 可选属性 ?
        • 3️⃣ 函数参数中的 undefined
      • 四、null vs undefined 的实际使用约定(非常重要)
        • 🔹 业界常见约定(强烈推荐)
        • 示例
      • 五、常见坑(前端必踩)
        • ❌ 坑 1:直接访问可能为 null 的值
        • ✅ 正确方式:缩小类型(类型守卫)
        • ❌ 坑 2:DOM API
        • ✅ 正确写法
      • 六、! 非空断言(慎用)
      • 七、可选链 & 空值合并(TS + ES2020 神器)
        • 1️⃣ 可选链 ?.
        • 2️⃣ 空值合并 ??
      • 八、总结一句话(记住就行)
  • 实践应用

  • 《TypeScript》学习笔记
  • 数据类型
mamingjuan
2020-10-15
目录

null和undefined

# 一、null 和 undefined 在 TS 中是什么?

在 TypeScript 里:

null        // 一个值,表示“空”
undefined   // 一个值,表示“未定义”
1
2

它们 既是值,也是类型:

let a: null = null
let b: undefined = undefined
1
2

# 二、关键前提:strictNullChecks

现在99% 项目都开启了:

{
  "compilerOptions": {
    "strict": true
  }
}
1
2
3
4
5

等价于:

{
  "strictNullChecks": true
}
1
2
3

# 开 / 关的本质区别

# ❌ 未开启(老项目)

let s: string

s = null        // ✅ 不报错
s = undefined   // ✅ 不报错
1
2
3
4

👉 极其危险,类型形同虚设


# ✅ 开启(现代 TS 项目,默认)

let s: string

s = null        // ❌
s = undefined   // ❌
1
2
3
4

结论:

null 和 undefined 不再是所有类型的子类型


# 三、正确使用 null / undefined 的方式

# 1️⃣ 显式声明可空

let s: string | null
let t: string | undefined
let u: string | null | undefined
1
2
3
s = null
t = undefined
1
2

👉 必须用联合类型


# 2️⃣ 对象属性中的可选 vs undefined

# 可选属性 ?

interface User {
  name: string
  age?: number
}
1
2
3
4

等价于:

age: number | undefined
1

但不等价于 null

const u1: User = { name: 'Tom' }           // ✅
const u2: User = { name: 'Tom', age: 18 }  // ✅
const u3: User = { name: 'Tom', age: null } // ❌
1
2
3

👉 ? = 可能不存在,而不是 null


# 3️⃣ 函数参数中的 undefined

function foo(x?: number) {}
1

等价于:

function foo(x: number | undefined) {}
1
foo()
foo(undefined)
foo(1)
1
2
3

# 四、null vs undefined 的实际使用约定(非常重要)

# 🔹 业界常见约定(强烈推荐)

场景 用哪个 原因
变量未初始化 undefined JS 原生语义
参数可选 undefined ? 语法
对象字段缺失 undefined JSON 习惯
主动“置空” null 明确表达“空”
后端返回空值 null 数据库常见

# 示例

let currentUser: User | null = null // 当前无用户
1

比

let currentUser: User | undefined
1

语义更清晰


# 五、常见坑(前端必踩)

# ❌ 坑 1:直接访问可能为 null 的值

function printLength(s: string | null) {
  console.log(s.length) // ❌
}
1
2
3

# ✅ 正确方式:缩小类型(类型守卫)

function printLength(s: string | null) {
  if (s !== null) {
    console.log(s.length) // ✅
  }
}
1
2
3
4
5

或:

if (s) { } // ⚠️ 会排除 '' 0 false
1

# ❌ 坑 2:DOM API

const el = document.getElementById('app')
el.innerHTML = 'hi' // ❌
1
2

# ✅ 正确写法

const el = document.getElementById('app')

if (el) {
  el.innerHTML = 'hi'
}
1
2
3
4
5

或断言(你非常确定存在):

const el = document.getElementById('app')!
1

# 六、! 非空断言(慎用)

el!.innerHTML = 'hi'
1

含义:

“我保证它不是 null / undefined”

⚠️ 运行时不会帮你检查


# 七、可选链 & 空值合并(TS + ES2020 神器)

# 1️⃣ 可选链 ?.

user?.profile?.name
1

# 2️⃣ 空值合并 ??

const name = user.name ?? '匿名'
1

对比:

||   // 会把 '' 0 false 当成假
??   // 只关心 null / undefined
1
2

# 八、总结一句话(记住就行)

TS 不允许你“假装不存在 null / undefined”

你必须:

  • 用联合类型声明
  • 用判断缩小
  • 用 ?. / ??
  • 谨慎用 !
上次更新: 2026/01/07, 09:20:46
类型声明
keyof和typeof

← 类型声明 keyof和typeof→

Copyright © 2015-2026 Glitz Ma
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式