首页 > 解决方案 > 为什么我需要在声明中使用类型断言来将变量分配给 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

我使用 Typescript 游乐场检查了这些类型。

标签: typescript

解决方案


这是设计使然。如果不是这种情况,杂项类型的机制将显着不那么有用。例如:_

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

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

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 所指出的,这一切都在“缩小”下进行了描述。


推荐阅读