Currently, I am in the process of developing an Angular 7 application that utilizes the NGRX store. In our application, we have numerous entities, each with its own dedicated list view. I decided to explore using generics with the NGRX store to avoid writing repetitive selectors, actions, reducers, and so on for almost identical functionalities. Initially, I focused on actions and attempted to create a function that would generate a set of actions based on a generic type, but I am encountering difficulties.
// Ensuring type safety
enum AddTypeNames {
ADD_REQUEST = 'AddRequestAction',
ADD_SUCCESS = 'AddSuccessAction',
ADD_FAILURE = 'AddFailureAction',
}
// Constructing an object literal with a string key and Action as the value
function createAddActions<T>(featureName: string): { [key in AddTypeNames]: Action } {
class AddRequestAction implements Action {
readonly type = `[${featureName}] Add request`;
constructor(payload: { entity: T }) { }
}
class AddSuccessAction implements Action {
readonly type = `[${featureName}] Add success`;
constructor(payload: { entity: T }) { }
}
class AddFailureAction implements Action {
readonly type = `[${featureName}] Add error`;
constructor(payload: { error: HttpErrorResponse }) { }
}
return {
AddRequestAction,
AddSuccessAction,
AddFailureAction,
};
}
While working on this implementation, I encountered an error message in the editor:
(property) AddRequestAction: Action
Property 'type' is missing in type 'typeof AddRequestAction' but required in type 'Action'.ts(2741)
I am unsure about the meaning of this particular error, especially since it appears that the type is defined within the class. Is my approach correct? How can I effectively create actions with generic types? Moreover, is leveraging generics extensively considered a best practice in such scenarios?