Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

OtherActions<T> type and potentially update the Reducer type #4036

Closed
ricokahler opened this issue Mar 15, 2021 · 2 comments
Closed

OtherActions<T> type and potentially update the Reducer type #4036

ricokahler opened this issue Mar 15, 2021 · 2 comments

Comments

@ricokahler
Copy link

ricokahler commented Mar 15, 2021

New Features

What is the new or updated feature that you are suggesting?

OtherActions<T> type. (see #4025 (comment) for context)

Given the problem @phryneas states in his article, unions are definitely prone to errors.

I think it could be valuable to ship a type helper OtherActions<T> that has the purpose of creating a complement set of actions for a given reducer.

The implementation of OtherActions would look like this:

type OtherActions<T extends AnyAction> = { type: T extends T['type'] ? T : { type: unknown } }

And its usage would look like this:

type Actions = SendMessageAction | DeleteMessageAction;

export function chatReducer(
  state = initialState,
  action: Actions | OtherActions<Actions>
): ChatState {

  switch (action.type) {
    case SEND_MESSAGE:
      return {
        messages: [...state.messages, action.messages]
      }
    case DELETE_MESSAGE:
      return {
        messages: state.messages // etc etc
      }
    // NOTE: notice how it errors if this is commented out
    // default:
    //   return state
  }
}

TS Playground Link

Additionally, I think it could be beneficial to use OtherActions in the definition of Reducer<T>

export type Reducer<S = any, A extends Action = AnyAction> = (
  state: S | undefined,
  action: A | OtherActions<A>
) => S

Why should this feature be included?

This change here would make it so the action param includes the complement of any union given to it. This would force typescript users to return a default case.

image

TS Playground Link

What docs changes are needed to explain this?

This would be included in #4025

@ricokahler
Copy link
Author

Related: #3580

@timdorr
Copy link
Member

timdorr commented Mar 15, 2021

I don't think this is actually going to solve any problems. Instead of having them remember to add a default case to their reducer, they now have to remember to use this extra type. That still puts the onus on the user and just shifts where they have to remember these things. So, it's a net zero gain.

Nonetheless, we already have an open issue for this.

Duplicate of #3580

@timdorr timdorr closed this as completed Mar 15, 2021
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants