7

I am doing some refactoring of a redux store, and I wanted to create a "Factory" type that could be used to reduce duplicate code.

Currently, I have it as:

interface CommonFactory<T, S> {
  Payload: Partial<S>;
  Action: Action<T> & { payload: this['Payload'] };
  ActionCreator: ActionCreator<this['Payload']>;
}

which allows me to extract a bunch of common types by simply writing

interface AppState {
  key1: any;
  key2: any;
  key3: any;
}

type Factory = CommonFactory<AppTypes, AppState>;

type AppPayload = Factory['Payload'];
type AppAction = Factory['Action'];
type AppActionCreator = Factory['ActionCreator'];

However, I've realized that a Partial for the payload is not correct. I'd rather use a Pick so that the ActionCreator can specify the properties to be returned. This would need to be passed not by the Factory, but by the ActionCreator. Something like

const someActionCreator: AppActionCreator<'key1'> = (someData: any) => {
  return {
    type: SOME_ACTION_TYPE,
    payload: {
      key1: someData
    }
  }
}

But I'm not sure how to pass a generic to an indexed access type.

  • 1
    Does this answer your question? [How do I pass a generic value type accessed through an index in TypeScript?](https://stackoverflow.com/questions/62747325/how-do-i-pass-a-generic-value-type-accessed-through-an-index-in-typescript) – Stav Noy Feb 16 '22 at 13:19
  • That's the answer to your question: https://stackoverflow.com/a/75792683/3794085 – darkbasic Mar 20 '23 at 16:12

0 Answers0