Typescript 如何制作深型护卫?
我有以下类型:Typescript 如何制作深型护卫?,typescript,typeguards,Typescript,Typeguards,我有以下类型: 类型子项={ foo:number |空 } 类型Parent={ child:child | null } 我想制作一个类型保护,它接收Parent作为参数,并确定foo是否是一个数字。。。比如: const-guard=(父:父):父?.child?.foo是数字=>{ 返回isNumber(父项?.子项?.foo) } 我希望TS现在能够推断出parent.child不为空-这可能吗?您必须将其拼写出来,例如: const-guard=(父:父):父是{child:{f
类型子项={
foo:number |空
}
类型Parent={
child:child | null
}
我想制作一个类型保护,它接收Parent
作为参数,并确定foo
是否是一个数字。。。比如:
const-guard=(父:父):父?.child?.foo是数字=>{
返回isNumber(父项?.子项?.foo)
}
我希望TS现在能够推断出
parent.child
不为空-这可能吗?您必须将其拼写出来,例如:
const-guard=(父:父):父是{child:{foo:number}}=>{
返回isNumber(父项?.子项?.foo);
};
可以使用交叉点类型执行此操作,如下所示:
const-guard=(父:父):父是父&{child:child&{foo:number;};}=>{
返回isNumber(父项?.子项?.foo);
};
(始终可以为其定义类型,而不是内联交点。)