Typescript中用于可空类型的条件类型。

4

我想检查一个类型是否可为空,以及它的值是否有条件类型。

我尝试实现:

type IsNullable<T> = T extends null ? true : false;

然而,它似乎无法正常工作。

type test = IsNullable<number> // Returns false as it should
type test = IsNullable<number | null> // Returns false when it should be true

如何正确检查类型是否可为空?我尝试使用 T extends null | T 但也不起作用。


尝试按照此处建议的方式翻转条件: https://github.com/Microsoft/TypeScript/issues/29627 - raffaeleambrosio
1个回答

9
您可以将extends的左右两侧进行切换,因此:
type IsNullable<T> = null extends T ? true : false;

应该适用于您。


不,它不起作用,因为 IsNullable<number> 返回 true。但是如果我从 IsBoolean<T> = boolean extends T ? true : false 进行更改,那么它就可以工作了。似乎所有的东西都是扩展自 null? - Marc
3
@Marc,它确实有效。请确保启用了strictNullChecksPlayground - Aleksey L.
是的,@AlekseyL. 说得很对。如果您在 tsconfig.json 中不启用 strictNullChecks,则每种类型都会扩展为 null。 您应该真正设置 strict: null - phry

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接