我试图让我粘贴在下面的代码执行,但 Typescript 编译器似乎不相信我已经正确地确保一个接口(interface)可以根据我所做的检查转换为另一个接口(interface)。我需要做什么才能让它对这段代码满意?
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)
来强制转换,但这实际上禁用了所有不理想的类型检查。如果没有那个,有没有办法做到这一点?
最佳答案
您可以使用 type guard代替您现有的条件表达式。这将有助于通知编译器数据结构满足您在 control flow analysis 期间想要的标准。 .
function personHasAddress (person: Person): person is PersonWithAddress {
return typeof person.address === 'string';
}
function logAddresses (people: Person[]) {
for (const person of people) {
if (personHasAddress(person)) logAddress(person);
}
}
关于typescript - 如何告诉 Typescript 从一个不太严格的接口(interface)转换到一个更严格的接口(interface)是可以的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72705744/