首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >typescript redux:如何使用类型安全操作减少样板文件

typescript redux:如何使用类型安全操作减少样板文件
EN

Stack Overflow用户
提问于 2019-08-21 18:11:10
回答 1查看 163关注 0票数 0

我正在使用带有类型安全操作的typescript。我的代码库有很多重复的代码,如下所示:我看过类似的问题,但找不到答案。

怎样才能减少样板文件。

代码语言:javascript
复制
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>;
EN

回答 1

Stack Overflow用户

发布于 2020-01-15 12:13:08

既然这个库已经被设计为减少样板代码,那么您可以坚持使用API的次数越多,需要编写的样板代码就越少。如果您使用内置的createReducer应用程序接口,有一种方法可以避免将您的操作类型定义为字符串。也就是说,它们是从createAction返回的操作创建者中推断出来的。

您将它们分开,这似乎意味着您正在使用自己的缩减程序,这几乎就是为什么您要导出所有FeatureXAction类型的原因。这可以在最后完成,而不是单独完成,但实际上只会为每个文件节省一行,并且您仍然需要在结束时聚合它们。所有这些都会增加冗长和样板。

在类型安全操作之前,我们有比你更多的样板,因为我们的每个操作都是由一个接口定义的,然后每个操作创建者都会返回该接口的一个实现。虽然它非常明确,但它非常冗长。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57589287

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档