angulartypescriptngxs

NGXS typed raw state value


I cannot find an example in the NGXS documentation on how to type the state object.

I want to type the return value of the snapshot method of Store.

For example

this.store.snapshot().SOME_STATE_SLICE

Is there a way to achieve this?


Solution

  • You can define the slice you want to take a snapshot of it and it will be typed, for example if you have this state:

    interface UserStateModel {
      readonly name: string;
    }
    
    export const USER_STATE_TOKEN = new StateToken<UserStateModel>('user');
    
    @State<UserStateModel>({
      name: USER_STATE_TOKEN,
    })
    export class UserState {
      @Selector()
      static name(state: UserStateModel) {
        return state.name;
      }
    }
    

    You can then in your component do:

    const name = this.store.selectSnapshot(UserState.name);