【发布时间】:2020-01-15 15:25:00
【问题描述】:
为什么 TypeScript 不将对象成员的类型缩小应用于对象类型本身,以便可以将其传递给另一个需要缩小类型的函数?如何在不失去类型安全的情况下修复/规避这个问题?
小例子:
type A = { key: string | null};
type B = {key: string};
function func(a: B) {};
const a: A = {key:'abcd'};
if(typeof(a.key)==='string') {
a.key // has (narrowed) type 'string'
func(a); // still does not work
}
错误信息是:Types of property 'key' are incompatible. Type 'string | null' is not assignable to type 'string'.
【问题讨论】:
-
删除不
!。 -
@OrkhanAlikhanov 对不起,我修正了这个例子。
标签: typescript types type-narrowing