Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Better typings for reducers #210

Merged
merged 1 commit into from
Mar 11, 2019
Merged

Better typings for reducers #210

merged 1 commit into from
Mar 11, 2019

Conversation

kosmogradsky
Copy link
Contributor

Reducer in Redux is defined like so:

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

I think it would be better to define LoopReducer in a similar way so the action type is taken from the parameter and the parameter has the same default as Reducer

@bdwain
Copy link
Member

bdwain commented Feb 23, 2019

but reducers are called with all actions? Why would you ever provide a different type there?

@kosmogradsky
Copy link
Contributor Author

kosmogradsky commented Feb 26, 2019

You would want this to provide more exact type for better type inference in the reducer switch case. For example, in your app you can have:

type Action = {
  type: 'ACTION_ONE',
  payload: number
} | {
  type: 'ACTION_TWO',
  payload: string
} | {
  type: 'ACTION_THREE',
  payload: {
    property1: number,
    property2: string
  }
}

If you provide Action type to Reducer as a type parameter you'll get better type inference for payloads.

@bdwain
Copy link
Member

bdwain commented Feb 26, 2019 via email

@kosmogradsky
Copy link
Contributor Author

kosmogradsky commented Feb 27, 2019

You would still have a default case which returns the state unchanged. If all the members of Action union type are handled with respectful cases then the default case will have the action typed as never.

@bdwain
Copy link
Member

bdwain commented Mar 11, 2019

sorry for the delay. I was on vacation the last few weeks. Sounds good!

@bdwain bdwain merged commit 216587b into redux-loop:master Mar 11, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants