-1

I have a subject in my Angular Service,

itemClicked: Subject<MenuTab | MenuLaunchTab, MenuItem>;

The problem is, I want to pass MenuItem only when I pass MenuTab as my first parameter, while pass nothing as my second parameter when the first parameter is MenuLaunchTab.

I want to replicate what we do for function arguments:

function(tab: MenuTab | MenuLaunchTab, item?: MenuItem)
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122

1 Answers1

-1

You need to combine both of types instead of union usage.

itemClicked: Subject<MenuTab, MenuItem> & Subject<MenuLaunchTab>;

now itemClicked supports both Subject<MenuTab, MenuItem> and Subject<MenuLaunchTab> but neither Subject<MenuTab> nor Subject<MenuLaunchTab, MenuItem>.

A function should unite all possible types of its overrides. Unfortunately, it means there's no other way than

function(tab: MenuTab | MenuLaunchTab, item?: MenuItem)

What you can do is to detect types at the beginning and then split your flow.

function(tab: MenuTab | MenuLaunchTab, item?: MenuItem) {
  // or other check that fits, because their definition is unclear.
  const menuLaunchTab: MenuLaunchTab | undefined = item ? undefined : tab;
  const menuTab: MenuTab | undefined = item ? tab : undefined;
  if (menuTab) {
    handlerOfmenuTab(menuTab, item);
  } else if (menuLaunchTab) {
    handlerOfmenuLaunchTab(menuLaunchTab);
  }

}
satanTime
  • 12,631
  • 1
  • 25
  • 73
  • 1
    Providing an explanation of code is always welcome, and generally results in more upvotes and fewer downvotes than a line of code with no explanation. – Heretic Monkey May 04 '20 at 20:00