How to infer generic type arguments from function parameters in typescript?

400 Views Asked by At

The following function's parameter has a generic interface with many type arguments:

function func<V extends GenericInterface>(value: V) { // Error here. Type args are needed
  /** Do stuff ... ** /
}

Typescript wants me to explicitly pass type arguments to GenericInterface, but that would mean I have to duplicate all of its generic params in my function signature. If it had only a couple of type parameters it would be easy to do:

function func<P extends ParameterConstaint, V extends GenericInterface<P>>(value: V) {
  /** Do stuff ... ** /
}

But this GenericInterface has very complicated constraints and many parameters. Is there a way to make typescript infer the type arguments of IGunChain so I don't have to duplicate a very large interface?

More context:

I am attempting to create a GUN writeable store for a svelteJs app like so:

function createMapStore<C extends IGunChain>(ref: C) {
  const { update, subscribe } = writable<C>({} as C)

  ref.on(function (data, key) {
    if (data !== null) {
      update((store) => ({ ...store, [key]: data }))
    } else {
      update((store) => {
        delete store[key]
        return store
      })
    }
  })

  return {
    subscribe,
    update: (key, value) => ref.get(key).put(value),
  }
}

Here is a link to the relevant file on my app repo: https://github.dev/ricardo-rp/gun-budget/blob/bugfix/gunStore/src/lib/db/gunStore.ts

Manually setting the type params results in a very bulky interface. Using any results in no type inference for the created store.

0

There are 0 best solutions below