【问题标题】:Is there a way to enforce the interface definition in ngrx/store models (angular 2)?有没有办法在ngrx/store模型(角度2)中强制执行接口定义?
【发布时间】:2017-03-20 13:29:38
【问题描述】:

在不同的博文和官方 ngnx/store 文档链接的示例中,我发现以下方法是“标准”操作方式。登录后,我将发布与将用户添加到商店相关的代码。

所以首先我创建了一个 Appstore 接口,代表我们的应用程序处理的所有对象:

export interface AppStore {
 user: Observable<User>;
};

这是用户模型:

export interface User {
  id: number;
  username: string;
  email: string;
};

然后我为用户创建了一个 reducer(其中有效负载包含用户 ID、电子邮件和用户名)

export const user: ActionReducer<User> = (state: User, action: Action) => {
  switch (action.type) {
    case ADD_USER:
      return action.payload;
    default:
      return state;
  }
};

最后,我以这种方式从商店中选择“用户”对象:

  user : User;

  constructor(private store: Store<AppStore>) {

        this.user = <Observable<User>>this.store.select('user');
  } 

但是,如果我将 reducer 更改为以下代码,则无意义的属性会进入最终对象,即使我认为用户界面应该避免这种情况发生。

export const user: ActionReducer<User> = (state: User, action: Action) => {
  switch (action.type) {
    case ADD_USER:
      return Object.assign({},action.payload, meaninglessProperty = 'abcd');
    default:
      return state;
  }
};

所以,我的问题是:AppStore 界面只是一种可视化/理解我们应用程序的整体商店结构的方式,还是 ngrx 商店实际上检查 Appstore 中的属性是否尊重他们自己的界面契约?

  • 如果确实如此,我缺少什么?
  • 如果没有,我是否可以更改某些内容以确保在运行时强制执行接口定义?

我问这个是因为我有更复杂的场景,在这些场景中检查接口会使代码“更安全”,并且会大大降低出错的风险。

【问题讨论】:

    标签: angular ngrx


    【解决方案1】:

    您的问题与 ngrx 并没有真正的关系,而是更多地关注关于 Object.assign 的 Typescript 类型系统,不幸的是,这并没有涵盖您的情况 - 您也可以查看 github 上的此线程以获取更多详细信息问题:https://github.com/Microsoft/TypeScript/issues/10532

    【讨论】:

      猜你喜欢
      • 2017-10-08
      • 2020-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多