TypeScript:即使 strictNullChecks 为 false,我也可以检查类型是否包含 undefined 吗?

TypeScript: Can I check if a type contains undefined even when strictNullChecks is false?

我们在 redux-starter-kit 中遇到了一个问题,其中库的用户禁用了 strictNullChecks,并且我们的一个类型测试是短路的,returning 类型用于不同的情况。

这个测试应该return True-Parameter 或 False-Parameter 取决于 P 参数是否包含未定义。

这是当前代码:

type IfMaybeUndefined<P, True, False> = [undefined] extends [P] ? True : False;

所以我期待这两个 return "yes":

IfMayBeUndefined<number, "no", "yes">
IfMayBeUndefined<number|undefined, "yes", "no">

现在我问自己是否有另一种方法来测试它,即使使用 strictNullChecks: false

我不相信这是可能的。

名称 "strictNullChecks" 有点误导,因为它可能暗示它只是指示 TypeScript 编译器执行额外的检查并发出额外的警告。但是,它实际上改变了类型检查器的基本行为以及 nullundefined 类型的语义。根据 TypeScript Guide

In strict null checking mode, the null and undefined values are not in the domain of every type and are only assignable to themselves and any (the one exception being that undefined is also assignable to void). So, whereas T and T | undefined are considered synonymous in regular type checking mode (because undefined is considered a subtype of any T), they are different types in strict type checking mode, and only T | undefined permits undefined values. The same is true for the relationship of T to T | null.