【问题标题】:Typescript Interface as series of OR interfacesTypescript 接口作为 OR 接口系列
【发布时间】:2019-12-19 22:43:17
【问题描述】:

有一个接口可以是多个接口之一

interface a {x:string}
interface b {y:string}
interface c {z:string}
type all = a | b | c

后来一个对象满足all,因为它的类型是c

打电话

    if (obj.hasOwnProperty('z')) {
      return obj.z
    }

编译失败,因为:

类型“a”上不存在属性“z”。

你是怎么解决这个问题的?

【问题讨论】:

标签: javascript typescript interface


【解决方案1】:

如果在您的情况下,可以接受将 hasOwnProperty 替换为 in 并且您不想定义自定义类型保护 - in will do the job

interface a { x: string }
interface b { y: string }
interface c { z: string }
type all = a | b | c;

function foo(obj: all) {
  if ('z' in obj) {
    return obj.z; // obj type is narrowed to c
  }
  return undefined;
}

Playground

【讨论】:

    【解决方案2】:

    obj.hasOwnProperty('z') 本身并不能保证obj 满足接口c。假设obj 被声明为

    var obj = { x: "foo"; y: "bar"; z: true };
    

    在这种情况下,obj 满足 ab,但不满足 c,因为 obj.z 不是字符串。

    但是,您可以编写自己的类型保护来解决这个问题:

    function isC(obj: all): obj is c {
      return obj.hasOwnProperty('z');
      // or return 'z' in obj;
    }
    
    ...
    
    if (isC(obj)) {
      return obj.z; // this is fine
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-09
      • 2020-10-26
      • 2018-09-22
      • 2013-09-19
      • 2016-10-27
      • 2017-12-17
      • 1970-01-01
      • 1970-01-01
      • 2016-08-20
      相关资源
      最近更新 更多