Search code examples
javascripttypescriptinterfaceaurelia

best way to define callbacks on objects in Typescript?


I have a sidebar menu component with a service that holds items in the menu. Multiple sources can then alter the menu as they see fit.

Currently each item implements SidebarItem:

export interface SidebarItem {
    name: string,
    link: Route|string,
    icon ?: string
}

However I can catch certain events (click, hover) and would like to have an option to define a callback on the sidebar item itself.

I'd like to know the best way to accomplish this. Should I define two properties on the interface and let everyone decide how they implement it, or are there any options? I don't think sidebar items can be classes, since I don't want a new class for each sidebar item.

If it helps, I can also dispatch the events using the aurelia event aggregator.

PS: If this feels subjective, just read the title as "How to" instead. My proposed method is a wild guess and I don't think it's correct.


Solution

  • I ended up going with the following syntax on the interface:

    onClick?: (e: MyEvent) => void

    Thanks to Nitzan Tomer in the comments.