【问题标题】:How can I use the type guard of the parent interface in the type guard of the child interface?如何在子接口的类型保护中使用父接口的类型保护?
【发布时间】: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


    【解决方案1】:

    最简单的解决方案:只需交换它:

    function isExtendsBase(value: any): value is ExtendsBase {
      return  'bar' in value && typeof value.bar === 'boolean' && isBase(value);
    }           
    

    如果您确实希望首先进行条形检查,请重铸为任何。

    function isExtendsBase(value: any): value is ExtendsBase {
      return isBase(value) as any && 'bar' in value && typeof value.bar === 'boolean'  ;
    }
    

    【讨论】:

    • 这仍然需要isBase 的一些重复,因为我想首先检查value 是否真实。此外,如果示例更复杂,则可能会出现更多重复。
    • 我不知道你可以对类型保护本身进行类型转换! +1
    猜你喜欢
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    • 2011-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多