为什么我需要在声明中使用类型断言,将变量赋值为null



我很困惑,为什么下面变量a的类型不是LoadStatus,尽管我明确地将其放在声明中:

type LoadStatus = 'succeess'|'failure'|null;
let a: LoadStatus = null;
let b = null as LoadStatus;
a; // type is null
b; // type is LoadStatus

我使用打字游戏检查了这些类型。

这是经过设计的。如果不是这样的话,各种类型的机制的用处就会大大减少。例如:

type LoadStatus = 'success' | 'failure' | null;
let a: LoadStatus = null;
let b = null as LoadStatus;
a ; // type is null
b; // type is LoadStatus
// null is converted to 'failure', so that always a string is returned
type ConvertLoadStatus<T extends LoadStatus> = T extends null ? 'failure' : T;
type resultA = ConvertLoadStatus<typeof a>; // failure;
type resultB = ConvertLoadStatus<typeof b>; // 'success' | 'failure', not very helpful
a = 5; // a is still not assignable to other things than described, so typing still protects the variable

另一个例子是检查null或未定义时的if语句:

type ExampleType = {a: string, b: number} | null;
function doSomething(a: ExampleType) {
if(a != null) {
a // a is {a: string, b: number}
a.a // a can now be accessed
// How would we ever be able to access a if it always stayed ExampleType?
}
a.a // Object is possibly 'null'
}

编辑:正如@Boug所指出的,这一切都是在缩小范围内描述的。

这被称为收缩并集类型。

查看这里的文档,你就会明白为什么它是Docu

下面的例子很像你的缩小的例子

最新更新