I recently jumped into TypeScript to code my projects with React/Redux (-Saga) and something has bothered me.
As you can see in the code below, declaring an interface for each action looks fine as there isn't much inside the file but this might not look so good over time with more actions (e.g. edit/delete), especially for the type declaration.
actions/articles.ts
import { IArticle, IStoreAction } from '../../../interfaces';
import { createAction } from './createAction';
export enum ActionTypes {
createArticleRequested = 'articles/createArticleRequested',
createArticleSucceeded = 'articles/createArticleSucceeded',
createArticleFailed = 'articles/createArticleFailed',
}
interface ICreateArticleRequestAction {
type: ActionTypes.createArticleRequested,
article: IArticle;
}
interface ICreateArticleFailureAction {
type: ActionTypes.createArticleFailed,
error: string;
}
interface ICreateArticleSuccessAction {
type: ActionTypes.createArticleSucceeded,
article: IArticle;
}
export type ArticlesAction =
ICreateArticleRequestAction |
ICreateArticleSuccessAction |
ICreateArticleFailureAction;
export const createArticleRequest = (article: IArticle)
: IStoreAction<typeof article> => createAction(
ActionTypes.createArticleRequested,
article
);
export const createArticleSuccess = (article: IArticle)
: IStoreAction<typeof article> => createAction(
ActionTypes.createArticleSucceeded,
article
);
export const createArticleFailure = (error: string)
: IStoreAction<typeof error> => createAction(
ActionTypes.createArticleFailed,
error
);
I tried to develop a reusable solution that could be based on a single interface but it usaully came with its set of errors. Is there a better existing setup to make the whole thing cleaner and more reusable?
Thank you for your attention!