Automatically infer TypeScript types in switch statements

InstructorRares Matei

Share this video with your friends

Send Tweet

Using string literal types together with switch types, we can build powerful type guarded logic flows. In this lesson, we will look at how we can take advantage of this, and build a reducer that automatically infers the action and payload type based on which switch statement case we are in.

- -
~ 6 years ago

Just wondering, why not to use enums instead of strings? The flow will infer the correct type as well

Rares Mateiinstructor
~ 6 years ago

You are correct, I could have definitely used enums. Actually, the NgRx example app uses enums as the recommended approach, as you only have the string value declared in one place in that case: https://github.com/ngrx/platform/blob/master/projects/example-app/src/app/books/actions/collection-api.actions.ts

But in this case, I wanted to keep the lesson a bit simpler, as there's quite a lot going on already. So I opted to work with string literal types directly.

Yellow Tiger
~ 5 years ago

Qustion: Is it possible to get the ActionType from the return type of our action creators?

Something like this:

export function messagesFetchRequested(messageId: string) {
  return {
    type: actionTypes.MESSAGES_FETCH_REQUESTED,
    payload: messageId
  };
}

type Action = ReturnType<typeof messagesFetchRequested>

but in this example Action is:

type Action = {
    type: string;
    payload: string;
}
Rares Mateiinstructor
~ 5 years ago

Yep, that should work!