I'm facing a situation where I can logically determine the type of an object, but I end up having to use type assertion and create additional dummy variables to access type-specific properties correctly. Is there a more efficient approach to handle this?
export type EventTypeItem =
event1 |
event2;
enum Event {
Event1,
Event2
}
interface event1 {
readonly id: string;
}
interface event2 {
readonly caller: ICaller;
}
interface ICaller {
readonly id: string;
}
export interface IEvent {
readonly eventItem: EventTypeItem;
readonly eventType: Event;
}
// An instance of IEvent is passed to a component
let exampleUnknownEvent: IEvent; // To access id we'd either use '.id' or '.caller.id'
// But we don't know beforehand which Event this will be
// Within a function
const x = exampleUnknownEvent as event1; // This unnecessary assignment serves only for type assertion
const y = exampleUnknownEvent as event2; // Another unnecessary assignment just for type assertion
if (exampleUnknownEvent.eventType === Event.Event2) {
return x.caller.id;
} // Instead of 'x.caller.id,' I'd prefer to use exampleUnknownEvent.caller.id since we established the type in the 'if' condition.
// For example: exampleUnkownEvent.caller.id as event2