typescript - 为什么我需要在声明中使用类型断言来将变量分配给 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 游乐场检查了这些类型。
解决方案
这是设计使然。如果不是这种情况,杂项类型的机制将显着不那么有用。例如:_
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 所指出的,这一切都在“缩小”下进行了描述。
推荐阅读
- c# - 在异常过滤器中从服务中捕获错误
- reactjs - useState 不更新套接字值
- apache-kafka - 当来自kafka的数据时,无法在德鲁伊中读取数据json格式
- spring-boot - 没有惰性的 Spring + Hibernate = LazyInitializationException
- flutter - 如何正确使用 ObjectBox flutter store 打开和关闭?
- python - 数据框.set_index; TypeError:“str”和“int”的实例之间不支持“<”
- spring - 如何在单独的类中定义 FlatFileItemReader?
- ruby-on-rails - PDF中的德语变音符号
- python - 如何在隐藏查询集的同时显示存储帖子的所有详细信息
- go - 如何检查gorm raw语句生成的数据?