是否有类型安全的方法来访问 ngrx/store 中的商店成员?

Is there a type safe way to access store members in ngrx/store?

我一直在使用 angular2

浏览 ngrx/store 的文档

https://github.com/ngrx/store

https://github.com/ngrx/example-app

上面的示例应用暗示我应该使用以下方式访问商店的可观察成员:

counter: Observable<number>;
constructor(private store: Store<AppState>){
    this.counter = store.select('counter');
}

使用 'counter' 的字符串来访问对象成员感觉与 TypeScript 背道而驰。是否有类型安全的方法来访问商店成员?

如果你看select的实现:

export function select<T, R>(pathOrMapFn: any, ...paths: string[]): Observable<R> {
  let mapped$: Observable<R>;
  if (typeof pathOrMapFn === 'string') {
    mapped$ = pluck.call(this, pathOrMapFn, ...paths);
  }
  else if (typeof pathOrMapFn === 'function') {
    mapped$ = map.call(this, pathOrMapFn);
  }
  else {
    throw new TypeError(`Unexpected type ${ typeof pathOrMapFn } in select operator,`
      + ` expected 'string' or 'function'`);
  }
  return distinctUntilChanged.call(mapped$);
}

您会看到传递字符串等同于 pluck, but passing a selector function is equivalent to map - 这是类型安全的。

所以传递一个选择器函数。这就是 example app.

中所做的

使用你的例子:

counter: Observable<number>;
constructor(private store: Store<AppState>){
  this.counter = store.select(state => state.counter);
}