TypeScript 类型排除 null 包括未定义

TypeScript type exclude null include undefined

根据

https://www.typescriptlang.org/docs/handbook/utility-types.html#nonnullabletype

NonNullable

Constructs a type by excluding null and undefined from Type.

例子
type T0 = NonNullable<string | number | undefined>;
//    ^ = type T0 = string | number
type T1 = NonNullable<string[] | null | undefined>;
//    ^ = type T1 = string[]

我读到它的定义是:

type NonNullable<T> = T extends null ? never : T

现在,我想排除 null 但包含我的代码所需的 undefined

你会怎么做?谢谢。

实际上现有的NonNullable定义为type NonNullable<T> = T extends null | undefined ? never : T;。但是您可以创建自己的实用程序类型,如下所示,并使用它。

type NonNullButUndefined<T> = T extends null ? never : T;

// Usage
type T = NonNullButUndefined<string | null | undefined>;

用法: