0

I'm trying to type out my AppState(first time).

My app state only has one store.select('sunDial') which is an Object that I'm really lost on how to properly add types when you select a slice from AppState.

Question: How can I properly add types to this simple example of a component and AppState.

I have a component:

import { Component, ChangeDetectionStrategy, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { AppState, SunDial } from '../app.interface';
import { Observable } from 'rxjs';

@Component({
  selector: 'sun-dial',
  templateUrl: 'sun-dial.component.html',
  styleUrls: ['sun-dial.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class SunDialComponent implements OnInit {
  private partOfDay: Observable<SunDial>; // is this an Observable??
  public activeInputField: SunDial; // Is this really referencing as a number?

  constructor(private store: Store<AppState>) { // I see this everywhere

    this.partOfDay = store.select<SunDial>('sunDial'); // select sunDial:SunDial?
  }
  ngOnInit() {
    this.partOfDay.subscribe(x => {
      this.activeInputField = x; 
    });
  }
}

And my AppState.ts

export interface AppState {
  sunDial: SunDial; // store.select('sunDial') create an object/observable?
}

export interface SunDial { // Is this really an Observable?
  activeInputField: number
}

Nothing in my WebStorm IDE is throwing errors but I really don't know how to reason about the types (basically just guessing). Could anyone help me understand how to completely annotate the types for my class SunDialComponent{}

Ref: what is store.select in ngrx

Community
  • 1
  • 1
Armeen Moon
  • 18,061
  • 35
  • 120
  • 233

1 Answers1

2

If you take a look to the select interface :

export interface SelectSignature<T> {
  <R>(...paths: string[]): Observable<R>;
  <R>(mapFn: (state: T) => R): Observable<R>;
}

You'll notice that you can either pass a string or a function.

So instead of passing a string to the select method, pass a function like that :

this.store.select(state => state.sunDial);

You'll notice that your IDE will understand that the result of this line will be of type Observable<SunDial>.

maxime1992
  • 22,502
  • 10
  • 80
  • 121