我有以下函数,将三种类型之一的参数作为参数。通过类型比较,我选择了正确的响应形状,如下所示。
const buildAddress = (
address: VerifiedStandardAddress | VerifiedExtendedAddress | Address
): Record<string, unknown> => {
if (typeof address !== Address.name) {
return {
city: address.city,
line1: address.address_line_1,
line2: address.address_line_2,
last_line: address.address_last_line,
postal_code: address.postal,
postal_ext: address.postal_ext,
state: address.region
}
}
return {
city: address.city,
line1: address.line1,
line2: address.line2,
postal_code: address.postal_code,
state: address.state
}
}
但是,打字稿编译器会抱怨,例如,
Property 'state' does not exist on type 'VerifiedExtendedAddress'
。它是正确的。此属性存在于类型 Address
上。
有没有办法避免这种情况,而不是将这段代码分成两个函数?
要么
typeof address !== Address.name
并不总是匹配 VerifiedExtendedAddress
,要么 Typescript 的智能无法推断隐式类型,因为关系太复杂。
在第一种情况下,您需要编辑 if 子句,使其始终与 VerifiedExtendedAddress 匹配。 在第二种情况下,您需要更强的类型保护。一个非常明确的类型保护函数可能如下所示:
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
}
然后您可以调用 isFish(...) 并确保捕获“鱼案例”。