Skip to content

TransactionWithMutations is missing operation based type when used with array methods #804

@godiagonal

Description

@godiagonal
  • I've validated the bug against the latest version of DB packages

Describe the bug
Some type information gets lost in TransactionWithMutations['mutations'] when used with array methods such as .map().

To Reproduce

const schema = z.object({
  id: z.string(),
  title: z.string(),
  completed: z.boolean(),
});

const todosCollection = createCollection(
  electricCollectionOptions({
    id: 'todos',
    schema,
    getKey: (item) => item.id,
    shapeOptions: {
      url: '/api/todos',
      params: { table: 'todos' },
    },
    onDelete: async ({ transaction }) => {
      await Promise.all(
        transaction.mutations.map((mutation) =>
          // ❌ `original` is typed as `{} | { id: string; title: string; completed: boolean; }`
          api.todos.delete(mutation.original.id),
        ),
      );

      // ✅ `original` is typed as `{ id: string; title: string; completed: boolean; }`
      await api.todos.delete(transaction.mutations[0].original.id);

      // ✅ `original` is typed as `{ id: string; title: string; completed: boolean; }`
      await api.todos.delete(transaction.mutations[1]!.original.id);
    },
  }),
);

Expected behavior
The type of transaction.mutations.map((mutation) => mutation.original)[0] should match transaction.mutations[0].original.

Additional context
Omitting mutations from Transaction<T> in TransactionWithMutations does the trick:

export type TransactionWithMutations<T extends object = Record<string, unknown>, TOperation extends OperationType = OperationType> = Omit<Transaction<T>, 'mutations'> & {
    mutations: NonEmptyArray<PendingMutation<T, TOperation>>;
};

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