【发布时间】:2019-10-23 23:20:09
【问题描述】:
我有两个接口,一个父接口和一个扩展它的接口:
interface Base {
foo: boolean;
}
interface ExtendsBase extends Base {
bar: boolean;
}
我有一个用户定义的基类类型保护:
function isBase(value: any): value is Base {
return value && 'foo' in value && typeof value.foo === 'boolean';
}
我想在编写ExtendsBase 接口的类型保护时使用该类型保护:
function isExtendsBase(value: any): value is ExtendsBase {
return isBase(value) && 'bar' in value && typeof value.bar === 'boolean';
} ~~~
表达式的第一部分 isFoo(value) 的计算结果为 value: Base。对于表达式的第二部分,isFoo(value) && 'bar' in value 的计算结果为 value: never。在完整的表达式中,我收到以下错误:
“从不”类型上不存在属性“bar”。
这里的目标是能够使用isExtendsBase 中的isBase 中的代码来遵循DRY 原则,并且在示例中可能比这个复杂得多。这个可以吗?
【问题讨论】:
标签: typescript