You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中为何用undefined或null扩充类型无效果?T1、T2、T3为何等价?

TypeScript中联合undefined/null无效果的原因分析

问题1:为什么在TypeScript中为类型添加undefined或null没有效果?

核心原因是你关闭了TypeScript编译配置里的strictNullChecks选项。

当strictNullChecks处于关闭状态时,TypeScript会把undefined和null视为所有类型的子类型——也就是说,任何类型默认都已经包含这两个值。这时候你手动给类型加上| undefined或者| null,本质上没有扩大原类型的取值范围,所以看起来完全没效果。

问题2:为什么代码中的T1、T2和T3是等价的?

看这段代码:

type T1 = number
type T2 = T1 | undefined // is still just number
type T3 = T1 | null      // is still just number

还是因为strictNullChecks关闭的缘故:

  • 关闭该选项时,number类型本身就已经允许undefined和null值,所以number | undefined和number | null和纯number类型的取值范围完全一致,TypeScript会直接把它们判定为等价类型。

如果你开启strictNullChecks选项,情况就不一样了:

  • T2会变成number | undefined,允许赋值为数字或undefined;
  • T3会变成number | null,允许赋值为数字或null;
  • T1只能赋值为数字,三者不再等价。

内容的提问来源于stack exchange,提问作者citykid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 05:34:55