Javascript Typescript接口作为一系列或接口

Javascript Typescript接口作为一系列或接口,javascript,typescript,interface,Javascript,Typescript,Interface,有一个接口可以是许多接口中的一个 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” 如何解决这个问题?obj.hasOwnProperty('z')本

有一个接口可以是许多接口中的一个

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”

如何解决这个问题?

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

var obj = { x: "foo"; y: "bar"; z: true };
在这种情况下,
obj
满足
a
b
,但不满足
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
}

如果在您的情况下,可以将
hasOwnProperty
替换为
中的
,并且您不想在
中定义自定义类型的防护装置-


hasOwnProperty
不是类型保护:
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;
}