Typescript 中可空的条件类型

Conditional types for nullable in Typescript

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

我尝试实施

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 也没有用。

可以切换extends的左右两侧,所以

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

应该适合你。