[英]Typescript: define a type that can't hold anything
I'm interested (for the purpose of validation) in such a type, that variables of this type cannot have any value assigned to them. 我对这种类型感兴趣(出于验证的目的),这种类型的变量不能具有任何赋值。 There is type
void
, but value of this type can contain the value undefined
, so it's not exactly what I'm asking about. 有
void
类型,但此类型的值可以包含undefined
值,所以这并不是我要问的。
It seems that I'm able to reproduce this behaviour used the intersection of incompatible types: 似乎我能够使用不兼容类型的交集来重现此行为:
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
But this looks more like a hack. 但这看起来更像黑客。 Maybe there is something more clear?
也许还有更清楚的东西? Or is this the right way?
还是这是正确的方法?
The type you are looking for is the never
type. 您要查找的类型是
never
类型。 From the docs : 从文档 :
The never type is a subtype of, and assignable to, every type;
never类型是每种类型的子类型,并且可以分配给每种类型。 however, no type is a subtype of, or assignable to, never (except never itself).
但是,任何类型都不是(永远不会除外的)永不的子类型或可分配给它的子类型。 Even any isn't assignable to never.
甚至任何东西都不能分配给永不。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.