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

How to type redux state and selectors with readonly? #638

Closed
mattg95 opened this issue Nov 14, 2023 · 3 comments
Closed

How to type redux state and selectors with readonly? #638

mattg95 opened this issue Nov 14, 2023 · 3 comments

Comments

@mattg95
Copy link

mattg95 commented Nov 14, 2023

Redux state is supposed to be immutable, so I've defined the state in my reducers like this

import { createReducer } from 'typesafe-actions';

const reducer = createReducer<Readonly<MyType>(defaultState)
    .handleAction(....

However, when I define a selector I want it to return the type without the Readonly modifier, so it's less verbose. Currently I do it with type casting like this:

import { createSelector } from 'reselect';

const selector = createSelector(state, (data) => data as MyType)

How do I do this without type casting the selector?

@EskiMojo14
Copy link
Contributor

it's not possible without casting - though i'd argue that it would make sense to keep the readonly modifier as you're not meant to modify data that comes out of a selector.

@mattg95
Copy link
Author

mattg95 commented Nov 14, 2023

Many thanks @EskiMojo14, do you have any more explanation or links about this?

you're not meant to modify data that comes out of a selector.

@EskiMojo14
Copy link
Contributor

you said it yourself:

Redux state is supposed to be immutable

even though you've selected it with a selector, it's still redux state, and still should be immutable. mutating state leads to unexpected behaviour, which is why Redux Toolkit uses Immer to actually freeze the state (meaning an error is thrown if mutation is attempted) and includes a middleware to track attempted mutations.

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

No branches or pull requests

2 participants