我正在尝试执行我下面粘贴的代码,但是TypeScript编译器似乎并不相信我已经正确地确保了一个接口可以基于我所做的检查转换为另一个。我需要做什么才能使它对这段代码满意?
interface Person {
name: string,
address?: string
}
interface PersonWithAddress extends Person {
address: string
}
function tryLoggingAddresses(people: Array<Person>) {
people.forEach(person => {
if (person.address) {
logAddress(person)
}
})
}
function logAddress(personWithAddress: PersonWithAddress) {
console.log(personWithAddress.address)
}
Typescript错误:
error TS2345: Argument of type 'Person' is not assignable to parameter of type 'PersonWithAddress'.
Types of property 'address' are incompatible.
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
63 logAddress(person)
我知道我可以通过更改该行代码为logAddress(person as PersonWithAddress)
来强制进行类型转换,但这实际上禁用了所有的类型检查,这并不理想。有没有什么方法可以在不进行这种类型转换的情况下实现呢?
function isPersonWithAddress(object: Person): object is PersonWithAddress { return 'address' in object; }
。像这样调用它:if (isPersonWithAddress(person)) { logAddress(person); }
。 - D M