Typescript中可为空的条件类型

问题描述 投票:1回答:1

我想检查一个类型是否可以为空,并且该值是否具有条件类型。

我尝试实现

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,但也不起作用。

typescript types conditional-statements nullable
1个回答
3
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.