我有以下代码,即使使用is
操作符,我也无法缩小类型范围.我try 使用isPerson
fn来声明它是Person type
,但是在函数中,我如何访问特定的属性以知道它是否是这种类型?
interface Person {
age: number;
}
interface Animal {
color: string
}
const test = (arg: Person | Animal): Person | Animal => {
return arg;
}
const isPerson = (num: Person | Animal): num is Person => {
return !!num.age;
}
var person = test({ age: 12 });
if(isPerson(person)){
person.age;
}
我在isPerson中得到的错误是
Property 'age' does not exist on type 'Person | Animal'.
Property 'age' does not exist on type 'Animal'.(2339)