【问题标题】:Conditional types for nullable in TypescriptTypescript中可为空的条件类型
【发布时间】:2020-01-07 18:45:45
【问题描述】:

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

我尝试实现

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】:

extends可以左右切换,所以

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

应该适合你。

【讨论】:

  • 不,它不起作用,因为IsNullable&lt;number&gt; 返回 true。但是,如果我从 IsBoolean&lt;T&gt; = boolean extends T ? true : false 更改,那么它可以工作。似乎一切都扩展为空?
  • @Marc,它确实有效。确保启用strictNullChecksPlayground
  • 是的,@AlekseyL。有一个好点。如果您没有在tsconfig.json 中启用strictNullChecks,则每种类型都会扩展为空。你真的应该在那里设置strict: null
猜你喜欢
  • 2020-03-29
  • 1970-01-01
  • 2018-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-17
  • 1970-01-01
  • 2019-02-10
相关资源
最近更新 更多