首页 > 解决方案 > 在 NgRx 中强类型化存储的目的是什么?

问题描述

CoreModule 是一个预先加载的模块,包含应用程序启动时所需的状态。

import * as fromCore from './state/core.reducer';

@NgModule({
  ...
  imports: [
    StoreModule.forRoot({ core: fromCore.reducer }),

DocumentModule 是一个延迟加载的模块。

import * as fromDocument from './state/document.reducer';

@NgModule({
  ...
  imports: [
    StoreModule.forFeature('document', fromDocument.reducer),

DocumentComponent 注入存储。

import * as fromDocument from './state/document.reducer';

constructor(private store: Store<fromDocument.State>) { }

fromDocument.State 扩展了“核心”状态。

import * as fromCore from '../../core/state/core.reducer';

export interface State extends fromCore.State {
    document: DocumentState;
}

这是一种我看到到处都在使用的方法,但我认为它没有任何好处。当我将它设置为 fromDocument.State 不扩展 fromCore.State 时,我仍然可以访问 DocumentComponent 中状态树的“核心”部分。

this.user$ = this.store.select(fromCore.getUser);

通过将存储注入组件中,我始终可以访问完整的状态树,无论我如何键入存储。那么强类型存储的目的究竟是什么?为什么不到处使用 Store<any> 呢?我与 store 对象交互的唯一方法是 store.select 和 store.dispatch 所以就我所见没有打字好处?

标签: angularstorestrong-typing

解决方案


具体点

在您提到的特定情况下,键入将有助于select将映射函数作为参数的重载,例如this.store.select(s => ....).

不过,NgRx 仍然允许您进行无类型选择。GitHub 上的相关讨论:https ://github.com/ngrx/store/issues/60

一般来说

TypeScript 和其他花哨的东西(公平地说,所有编程语言的大多数特性)的强类型化并不意味着

  • 自动验证您的程序
  • 充当某种安全功能(防止数据泄露)

相反,它们是我们可怜的人类开发人员的拐杖,以避免犯我们通常在自己的代码中编写的愚蠢错误。

示例:就像尝试调用user.namme而不是user.name在代码的晦涩,被遗忘的部分中调用,这将导致一连串的错误。想象一下,它只向用户显示一些“未定义”和“登录错误”,在一个陌生的地方,并且只有当他按照一定的顺序执行 5 个非常具体的操作时,有点难以追溯和重现。

如果您使用强类型,编译器会在投入生产之前快速检测到这一点。


推荐阅读