本篇介绍 TypeScript 实用类型中的 NonNullable<Type>
类型。NonNullable
会从传入的类型中将 null
和 undefined
排除,之后把剩下的成员构造成一个新类型。
下面是一个简单的例子:
type U1 = string | number | undefined;
type T0 = NonNullable<U1>;
上面的代码中定义了一个名为 U1
的联合类型,NonNullable
会将该类型中的 undefined
排除,再将剩余的成员构造成新的类型 T0
,类型 T0
等价于下面的类型:
type NewT0 = string | number;
再看一个包含成员 null
的例子:
type U2 = string[] | null | undefined;
type T1 = NonNullable<U2>;
上面的类型 U2
中包含成员 null
,因此 NonNullable
会把 null
和 undefined
都排除掉,构造的新类型便是 string[]
。类型 T1
等价于下面的类型:
type NewT1 = string[];
NonNullable
的类型定义源码中通过 extends
实现,源码如下:
/**
* Exclude null and undefined from T
*/
type NonNullable<T> = T extends null | undefined ? never : T;
never
表示从来不会出现的值的类型,因此联合类型的当成员为 null
或 undefined
时,NonNullable
会将他们排除,只留下联合类型中的其他成员,通过保留下来的成员构造新的类型,也就是源码中的 T
类型。
One comment
2025年10月新盘 做第一批吃螃蟹的人coinsrore.com
新车新盘 嘎嘎稳 嘎嘎靠谱coinsrore.com
新车首发,新的一年,只带想赚米的人coinsrore.com
新盘 上车集合 留下 我要发发 立马进裙coinsrore.com
做了几十年的项目 我总结了最好的一个盘(纯干货)coinsrore.com
新车上路,只带前10个人coinsrore.com
新盘首开 新盘首开 征召客户!!!coinsrore.com
新项目准备上线,寻找志同道合的合作伙伴coinsrore.com
新车即将上线 真正的项目,期待你的参与coinsrore.com
新盘新项目,不再等待,现在就是最佳上车机会!coinsrore.com
新盘新盘 这个月刚上新盘 新车第一个吃螃蟹!coinsrore.com