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

[Basic] useReducer: type safe dispatcher call #615

Closed
Taschenbuch opened this issue Mar 16, 2023 · 2 comments
Closed

[Basic] useReducer: type safe dispatcher call #615

Taschenbuch opened this issue Mar 16, 2023 · 2 comments
Assignees
Labels
BASIC Basic Cheatsheet

Comments

@Taschenbuch
Copy link

What cheatsheet is this about? (if applicable)

Basic cheatsheet

What's your issue or idea?

Suggestion for useReducer on this page:
https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/hooks/#usereducer

You can make the dispatch() call type safe too by using a const as parameter with type information. That can be helpfull when you have a lot of dispatchers and you need to refactor some later:

instead of this:
onClick={() => dispatch({ type: "decrement", payload: "5" })}

you could do this:
onClick={() => {const action: ACTIONTYPE = { type: "decrement", payload: "5" }; dispatch(action);}}

awesome page. helped me a lot to migrate my react js to typescript.

@Taschenbuch Taschenbuch added the BASIC Basic Cheatsheet label Mar 16, 2023
@filiptammergard
Copy link
Collaborator

Hey @Taschenbuch! Not sure how this would improve type safety. You can see in the playground that the dispatch function is already type safe.

Try changing type do something that is not included in ACTIONTYPE or changing payload to something that's not supported by that type—TypeScript will tell you something is wrong.

Great to hear that the cheatsheet has helped you! Feel free to comment if you still think something could be improved.

@Taschenbuch
Copy link
Author

my fault. you are right. I did not notice and did not expect it to be type safe out of the box. nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
BASIC Basic Cheatsheet
Projects
None yet
Development

No branches or pull requests

3 participants