TypeScript:定义可以是 bool 或 null 的类型 [英] TypeScript: Define type that can be bool or null

查看:37
本文介绍了TypeScript:定义可以是 bool 或 null 的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以返回 true、false 或 null 的函数.

I have a function that can return either true, false or null.

我如何定义这种类型?现在,作为临时解决方案,我将其定义为 boolean |字符串,但它具有误导性,有人可能认为它真的可能返回字符串......有什么想法吗?

How do I define this type? For now, as a temporary solution, I define it as boolean | string, but it's misleading, someone may thing that it really may return string... Any ideas?

推荐答案

这取决于您使用的打字稿版本.

It depends on which typescript version you are using.

  • 在 2.0 之前 null 可以在任何类型上返回(在域中"),所以 boolean 是你的类型

  • before 2.0 null can be returned on ("is in the domain of") any type, so boolean is your type

从 2.0 开始,如果启用 --strictNullChecks 那么你必须指定一个类型可以返回 null.所以你的类型将是 boolean |null

starting with 2.0, if you enable --strictNullChecks then you have to specify that a type can return null. So your type will be boolean | null

更多详情此处 段落不可为空的类型

这篇关于TypeScript:定义可以是 bool 或 null 的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆