Get the type from a - "createAction" function

Viewed 846

There are two ways of creating an ngrx Action. One is to define a new class that implements the Action class and the other is to use the "createAction" function. Is there a way to get to the typings of an action that was created using the "createAction" method?

For example if I have this action:

export const getWorker = createAction(
  '[Worker Api] Get Worker',
  props<{ workerId: number }>()
);

I would like to get the workerId in an effect that listens to that action:

getWorker$ = createEffect(() => {
return this.actions$.pipe(
  ofType(WeatherApiActions.getWorker),
  switchMap((action: { type: string, workerId: number }) => this.workerService.getWorker(action.workerId)),
  map((worker: IWorker) => WeatherApiActions.getWorkerSuccess({ worker }))
)})

As you so I had to write the type myself. This makes the effect tightly coupled to the action and this is a huge drawback. So my question is: Do I must use the first way of creating an action in order to have the action payload typings?

1 Answers

I'm relatively new to ng/ngrx and the like, but it seems that part of the reason for using the create* helper methods is to get better type support. I had this same issue and one of my effects went from this:

  authSignup = this.actions$.pipe(
    ofType(AuthActions.SIGNUP_START),
    switchMap((signupAction: AuthActions.SignupStart) => {
      return this.http.post<AuthResponseData>(
  ...

To this:

  authSignup = createEffect(() =>
    this.actions$.pipe(
      ofType(AuthActions.signupStart),
      switchMap(({ email, password }) => {
        return this.http
          .post<AuthResponseData>(
  ...

The action looks like:

export const signupStart = createAction(
  "[Auth] Signup Start",
  props<{ email: string; password: string }>()
);

It took a bit for me to figure this out; the switchMap now knows what the props for the action are. And, at least in the latest VSCode, I got IntelliSense help when entering the parameters.

Related