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

Type narrowing for selection + item api #16

@Kelin2025

Description

@Kelin2025

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions