i those interfaces:
export interface EventCollectorData {
eventType: EventCollectorType;
}
export interface ClickEventCollectorData extends EventCollectorData {
elementData: EventCollectorElementLocator;
eventType: EventCollectorType.CLICK;
}
export interface NetworkEventCollectorData extends EventCollectorData {
eventType: EventCollectorType.REQUEST;
requestData: {
method: NetworkMethod;
url: string;
headers: Object;
body: {
json: Object | null;
text: string | null;
formData: any;
};
};
}
export type EventCollectorDataType = ClickEventCollectorData | NetworkEventCollectorData;
When I want to use the EventCollectorDataType and check if elementData
or requestData
is exists I'm getting this error:
Property 'elementData' does not exist on type 'EventCollectorDataType'. Property 'elementData' does not exist on type 'NetworkEventCollectorData'.
Here is an example for the function I want to do this check:
const check = (eventCollector: EventCollectorDataType) {
if (eventCollector.elementData) {
} else if (eventCollector.requestData) {
}
}
How can I implement something like that?
CodePudding user response:
You need to narrow down what type you're dealing with before you access properties that only exist on one part of the union. The way you've set things up, the eventType
property is perfect for this (it forms a discriminated union), so I recommend the following:
const check = (eventCollector: EventCollectorDataType) {
if (eventCollector.eventType === EventCollectorType.CLICK) {
// do stuff with eventCollector.elementData
} else if (eventCollector.eventType === EventCollectorType.REQUEST) {
// do stuff with eventCollector.requestData
}
}
An alternative way to narrow it down would be like this:
if ('elementData' in eventCollector) {
} else if ('requestData' in eventCollector) {
}