打字稿:定义一个不能容纳任何东西的类型

时间:2018-07-25 03:59:09

标签: typescript

我对这种类型感兴趣(出于验证目的),这种类型的变量不能分配任何值。有类型void,但是此类型的值可以包含值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

但这看起来更像是黑客。也许还有更清楚的东西?还是这是正确的方法?

1 个答案:

答案 0 :(得分:2)

The type you are looking for is the never type. From the docs:

The never type is a subtype of, and assignable to, every type; however, no type is a subtype of, or assignable to, never (except never itself). Even any isn’t assignable to never.

相关问题