typescript - Typescript:定义一个不能容纳任何东西的类型
问题描述
我对这种类型感兴趣(出于验证的目的),这种类型的变量不能有任何值分配给它们。有 type void
,但是这个 type 的 value 可以包含 value undefined
,所以这不是我要问的。
似乎我能够使用不兼容类型的交集来重现这种行为:
type nothing = true & false;
const nothingTrue: nothing = true; // error, true not assignable to false
const nothingFalse: nothing = false; // error, false not assignable to true
const nothingUndefined: nothing = undefined; // error, undefined not assignable to true
但这看起来更像是一个黑客。也许有更清楚的事情?或者这是正确的方法?
解决方案
您正在寻找的类型就是never
类型。从文档:
never 类型是每个类型的子类型,并且可以分配给每个类型;但是,没有类型是 never 的子类型或可分配给 never(never 本身除外)。甚至 any 也不能分配给 never。
推荐阅读
- python - 反转彩色图片?
- android - 如何将资产中的数据库移动到应用程序数据库?
- reactjs - Chrome 不会在 React 应用中保存 Express cookie
- python - 代码未输入带有有效语句的 if 语句且未退出 while 循环
- python - 有没有办法在 python 中测试竞争条件?
- r - 获取下一个迭代值而不是当前的闪亮值
- python - 我正在尝试制作一个小年龄游戏,但它关闭了
- python - AWS Boto3 IoT - 如何获取事物证书的内容
- javascript - 如何将在线模块/库添加到我的 React 文件中?
- javascript - 将一个数组中的数字与另一个数组中的数字进行比较并返回结果