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;
}