我正在使用带有类型安全操作的typescript。我的代码库有很多重复的代码,如下所示:我看过类似的问题,但找不到答案。
怎样才能减少样板文件。
import { action, ActionType, createAction } from 'typesafe-actions';
interface ModelA {
stuff: string
}
export enum FeatureAActionTypes {
Load = '[FeatureA] Load',
Success = '[FeatureA] Success',
Fail = '[FeatureA] Fail',
Reset = '[FeatureA] Reset'
}
export const FeatureAActions = {
load: createAction(FeatureAActionTypes.Load),
success: (response: ModelA[]) => action(FeatureAActionTypes.Success, response),
fail: (error: string) => action(FeatureAActionTypes.Fail, error),
reset: createAction(FeatureAActionTypes.Reset)
};
export type FeatureAAction = ActionType<typeof FeatureAActions>;
interface ModelB {
differentStuff: string
}
export enum FeatureBActionTypes {
Load = '[FeatureB] Load',
Success = '[FeatureB] Success',
Fail = '[FeatureB] Fail',
Reset = '[FeatureB] Reset'
}
export const FeatureBActions = {
load: createAction(FeatureBActionTypes.Load),
success: (response: ModelB[]) => action(FeatureBActionTypes.Success, response),
fail: (error: string) => action(FeatureBActionTypes.Fail, error),
reset: createAction(FeatureBActionTypes.Reset)
};
export type FeatureBAction = ActionType<typeof FeatureBActions>;
发布于 2020-01-15 04:13:08
既然这个库已经被设计为减少样板代码,那么您可以坚持使用API的次数越多,需要编写的样板代码就越少。如果您使用内置的createReducer
应用程序接口,有一种方法可以避免将您的操作类型定义为字符串。也就是说,它们是从createAction
返回的操作创建者中推断出来的。
您将它们分开,这似乎意味着您正在使用自己的缩减程序,这几乎就是为什么您要导出所有FeatureXAction
类型的原因。这可以在最后完成,而不是单独完成,但实际上只会为每个文件节省一行,并且您仍然需要在结束时聚合它们。所有这些都会增加冗长和样板。
在类型安全操作之前,我们有比你更多的样板,因为我们的每个操作都是由一个接口定义的,然后每个操作创建者都会返回该接口的一个实现。虽然它非常明确,但它非常冗长。
https://stackoverflow.com/questions/57589287
复制