gpt4 book ai didi

typescript - Typescript 中可空的条件类型

转载 作者:行者123 更新时间:2023-12-05 09:11:51 28 4
gpt4 key购买 nike

我想检查一个类型是否可以为 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;

应该适合你。

关于typescript - Typescript 中可空的条件类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59626785/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com