我试图让我粘贴在下面的代码执行,但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)
来强制转换,但这实际上禁用了所有不理想的类型判断.有没有办法做到这一点?