[英]Typescript property does not exist on type when using a type where property should exist
I am using a function which takes a message handler function as an argument.我正在使用一个将消息处理函数作为参数的函数。 The message handler is defined as:
消息处理程序定义为:
export declare type MessageHandler = <EventType extends AnyEventName = AnyEventName>(type: AnyEventName, payload: EventPayload<EventType>) => void;
In the code there is also the following definition:在代码中还有如下定义:
export declare type AnyEventPayload = EventPayload<AnyEventName>;
the message handler I am passing is defined as follows:我传递的消息处理程序定义如下:
(message_type: AnyEventName, payload: AnyEventPayload) => {
console.log(message_type, payload)
if (message_type === 'idCheck.applicantStatus' && payload.reviewStatus === 'completed')
{
router.push('/')
}
}
However I the IDE complains that Property 'reviewStatus' does not exist on type 'AnyEventPayload'. Property 'reviewStatus' does not exist on type '{}'.ts(2339)
但是,我的 IDE 抱怨
Property 'reviewStatus' does not exist on type 'AnyEventPayload'. Property 'reviewStatus' does not exist on type '{}'.ts(2339)
Property 'reviewStatus' does not exist on type 'AnyEventPayload'. Property 'reviewStatus' does not exist on type '{}'.ts(2339)
When I hover over AnyEventPayload
I get:当我将鼠标悬停在
AnyEventPayload
上时,我得到:
(alias) type AnyEventPayload = {} | {
idDocSetType: string;
types: string[];
videoRequired?: string | undefined;
} | {
idDocSetType: string;
} | {
applicantId: string;
} | {
reprocessing: boolean;
levelName: string;
creationDate: string;
expireDate: string;
reviewStatus: string;
autoChecked: boolean;
} | {
...;
} | {
...;
} | {
...;
} | SnsError
import AnyEventPayload
reviewStatus
is there so I don't understand why it's complaining or How can I fix this error? reviewStatus
在那里,所以我不明白为什么它在抱怨或者我该如何解决这个错误?
AnyEventPayload
is a union type (which means that it might be any of those type variations between the union operators ( |
). Because of this, the reviewStatus
property name might not be a part of the type, so in order to safely check that the payload
value is of the type that includes that property, you can use the in
operator to narrow the type to that specific variation. To do so, you just need to precede the equality check which accesses the property with an expression using the in
operator so that TS can be sure that the property exists before trying to access it and compare its value: AnyEventPayload
是联合类型(这意味着它可能是联合运算符 ( |
) 之间的任何类型变体。因此, reviewStatus
属性名称可能不是类型的一部分,因此为了安全地检查payload
值是包含该属性的类型,您可以使用in
运算符将类型缩小到该特定变体。为此,您只需在相等性检查之前使用in
运算符使用表达式访问属性,因此TS 在尝试访问它并比较它的值之前可以确保该属性存在:
if (
message_type === 'idCheck.applicantStatus'
// Add the following check to ensure that the property exists in the object
&& 'reviewStatus' in payload
&& payload.reviewStatus === 'completed'
) router.push('/');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.