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

6 messages · Page 1 of 1 (latest)

peak egret
#

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?

So far, the best solution I've (heard)[https://stackoverflow.com/questions/78209469/how-to-create-a-wrapper-for-solidjss-setstore-in-typescript?noredirect=1#comment137881170_78209469] is:

// @ts-expect-error
const setStoreWithEffect: SetStoreFunction<Foo> = (...params: [any]) => {
    console.log("setStore invoked with parameters:", params);
    return setStore(...params);
};

But the error suppression makes it ugly. Is there any clean way to do this?

nova yacht
#

You can directly get type of anything in ts with typeof. If you define your wrapper with same type as setStore is, then the arguments and return value get automatically typed

const setStoreWithEffect: typeof setStore = (...params) => setStore(...params)
indigo garnet
#

That does not work, because of type inference not being able to figure out if the generic is the same in both cases.

#

I've tried for my storage primitive makePersisted(signalOrStore).

peak egret
nova yacht
#

Oh so that's weird. Also I see that it's fine with

const setStoreWithEffect: typeof setStore = (...params: any[]) => {
  return setStore(params[0], params[1], params[2]);
}

But it's not what we want.
And I always treated spread operator as shorthand for this on variable number of arguments. I guess ts won't cover this case. For now if you just don't want these errors without // @ts-expect-error, you can also do

const setStoreWithEffect: typeof setStore = (...params: any[]) => {
  return (setStore as any)(...params);
}

I think it's fine to use as any internally in function as long as you know what you are doing and with properly set arguments / return value types, which typeof setStore takes care of.