Skip to content
This repository has been archived by the owner on Aug 9, 2024. It is now read-only.

Type narrowing for selection + item api #16

Open
Kelin2025 opened this issue Apr 18, 2023 · 1 comment
Open

Type narrowing for selection + item api #16

Kelin2025 opened this issue Apr 18, 2023 · 1 comment

Comments

@Kelin2025
Copy link
Member

Kelin2025 commented Apr 18, 2023

Suppose that we have a list of widgets. Widget looks like this:

type Widget = {
  id: string;
  type: string;
  options: Record<string, any>;
};

options type depends on widget type. For example

type SwapWidget = Widget & {
  type: 'swap';
  options: { from: string; to: string; value: number };
};

It'd be cool to create a single kv and then create sets of item apis for each widget type

export const widgets = createListApi<Widget, string>({
  keygen: (widget) => widget.id || `id-${Math.random().toString(36).slice(2, 10)}`,
});

export const swapWidgets = createSelection(
  widgets,
  (widget): widget is SwapWidget => widget.type === 'swap'
);

export const swapWidgetApi = createItemApi({
  kv: widgets,
  events: {
    fromChanged: widgets.mapItem(({ options }, from: string) => ({ options: { ...options, from } })),
    toChanged: widgets.mapItem(({ options }, to: string) => ({ options: { ...options, to } })),
    valueChanged: widgets.mapItem(({ options }, value: string) => ({ options: { ...options, value } })),
  },
});

However, we can't narrow swapWidgetApi to work with swap widgets only. And, as a result, types can't be narrowed too

What if we could create api directly from selection? Like swapWidgets.mapItem, or pass swapWidgets instead of widgets as kv param?

@Kelin2025
Copy link
Member Author

Kelin2025 commented Apr 18, 2023

Alternatively, we could create separate lists and combine them into one. Like:

export const swapWidgets = createListApi<SwapWidget, string>(...)
export const transactionsWidgets = createListApi<TransactionsWidget, string>(...)

export const allWidgets = combineLists({
  lists: [swapWidgets, transactionsWidgets]
})

This will solve type narrowing problems but we should also be able to create common api somewhere (like allWidgets.removeItem, for example)

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant