Typescript function argument with child/inherited class?
21:30 04 Mar 2022

I am trying to write a function that sets some properties on its arguments (not return a new object), the argument is of a class that extends from the same basecalss, i.e.:

class BaseEvent {
    string eventName!;
}

class DeleteEvent extends BaseEvent {
    string deleteReason;
}

class UpdateEvent extends BaseEvent {
    string updatedBy;
}

const modifyEvent = async (event: BaseEvent) {
    switch event.eventName {
        case "deleteEvent":
            event.deleteReason = "xyz"; // doesn't work deleteReason doesn't exist on base class
            return;

        case "updateEvent":
            event.updatedBy = "abc";
            return;
    }
}

I tried this:

switch (true) {
    case event instanceOf DeleteEvent:
        event.deleteReason = "xyz";   // doesn't work deleteReason doesn't exist on base class
        return;

    case event instanceOf UpdateEvent:   // still doesn't work
        event.updatedBy = "abc";
        return;
}

I've also tried typecasting

let modifiedEvent = event; //argument event

switch event.eventName {
    case "updatedEvent":
        modifiedEvent =  modifiedEvent; //no luck here either
}

Now there should be a simple/clean solution for this but sadly my patience is exhausting. Any suggestion would be very helpful. Again, I want to take an object of a child class, see if it's of type childA or childB, and if it's childA, then I update one property, and if it's childB, then I update another property, and these properties don't exist on both child types.

EDIT: also the function is async because based on what child class this is I'm doing some database read operations etc

javascript typescript