首页 > 解决方案 > 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

但这看起来更像是一个黑客。也许有更清楚的事情?或者这是正确的方法?

标签: typescript

解决方案


您正在寻找的类型就是never类型。从文档

never 类型是每个类型的子类型,并且可以分配给每个类型;但是,没有类型是 never 的子类型或可分配给 never(never 本身除外)。甚至 any 也不能分配给 never。


推荐阅读