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.