由于该参数是一个联合,因此您只能访问这两种类型的公共成员。自从
isFoo
两者都不存在,将无法访问。对于这个用例,您可以使用
in
键入guard以检查属性是否存在。
export class Foo {
isFoo: boolean;
}
export class Bar {
isBar: boolean;
}
function isFooBar(fooBar: Foo | Bar) {
if ('isFoo' in fooBar) {
// fooBar is of type Foo here
console.log("is foo " + fooBar.isFoo);
} else {
// fooBar is of type Bar here
console.log("is bar " + fooBar.isBar);
}
}