Search code examples
typescriptsolid-js

How to create a wrapper for SolidJS's setStore in TypeScript?


I have a SolidJS store defined:

const [store, setStore] = createStore<SomeComplexType>();

I need to run some code before every execution of setStore, so I would like to wrap it with my own function. Is there a way to do that that preserves all types and all overloads?

I've tried:

const setStore: SetStoreFunction<SomeComplexType> = (...args: Parameters<SetStoreFunction<SomeComplexType>>) => {
  setStore_(...args);
};

But I get an error:

A spread argument must either have a tuple type or be passed to a rest parameter.


Solution

  • The best solution I heard is using any[] for the parameter type and casting setStore to any. It preserves types and doesn't require suppression via annotations.

    TS Playground

    import { createStore, type SetStoreFunction } from "solid-js/store";
    
    type Foo = { foo: string };
    
    const [store, setStore] = createStore<Foo>({ foo: "bar" });
    
    const setStoreWithEffect: SetStoreFunction<Foo> = (...params: any[]) => {
      console.log("setStore invoked with parameters:", params);
      return (setStore as any)(...params);
    };
    

    Credits to Maciek50322.