question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Use generic to type the name of a slice

See original GitHub issue

Specifying a generic type for the property name of a slice would help typescript to deduce the type of objects built from slice.

As a practical example, I would like to put all my action creators inside an object I can then type and pass to Thunk extra arguments, or a react-redux mapDispatchToProps. This looks like this :

const clientSlice = createSlice({name:'clients', reducers: {get: (state) => {}}});
const categorySlice = createSlice({name:'category', reducers: {save: (state) => {}}});
const uiSlice = createSlice({name:'ui', reducers: {goToHome: (state) => {}}});

export const actionCreators = {
   [clientSlice.name]: {...clientSlice.actions},
   [categorySlice.name]: {...categorySlice.actions},
   [uiSlice.name]: {...uiSlice.actions}
}

export type ActionCreators = typeof actionCreators

If name was a generic extending string, I could have autocompletion in code like

const connectMyComponent = (dispatch: Dispatch) : MapDispatchToProp => (actionCreators : ActionCreators) => ({
   getClients: dispatch(actionCreators.clients.get()),
   saveCategory: dispatch(actionCreators.category.save()),
   changePage: dispatch(actionCreators.ui.goToHome())
})

Unfortunately, this won’t work since clientSlice.name is typed string.

There is a workaround you can see below, but integrating a generic type would be quite easy and straightforward (I can do a PR if wanted).

Workaround : It’s possible to wrap the function createSlice like describe here in rtk doc and return an object with a type for the property name :

const createGenericSlice = <
  Name extends string
  T,
  Reducers extends SliceCaseReducers<T>
>({
  name = "",
  initialState,
  reducers
}: {
  name: Name
  initialState: T
  reducers: ValidateSliceCaseReducers<T, Reducers>
}) => {
  const slice = createSlice({
    name,
    initialState,
    reducers: {
      ...reducers
    }
  });

  return slice as typeof slice & {name: Name};
}

const clientSlice = createGenericSlice({
  name: 'clients',
  initialState: { status: 'loading' } as GenericState<string>,
  reducers: {
    {get: (state) => {}}
  }
})

then typeof clientSlice ['name'] will be the literal ‘clients’.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:7 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
markeriksoncommented, Feb 19, 2020

The PR was merged in. It’ll get included in 1.3.0. I’ve got several other things I want in there first, so keep an eye on when that’s ready.

0reactions
markeriksoncommented, Feb 12, 2020

Sure, put up a PR and let’s look at it. Would help if you could include some tests that show the before and after results.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Generic functions on slices with Go type parameters
Using the type parameters proposal, writing a generic slice ... the function's name defines a type parameter for the function's use.
Read more >
Can I construct a slice of a generic type with different type ...
No. Given a parametrized Token type as: type Token[T any] struct { TokenType string Literal T }. each instantiation with a different type...
Read more >
An Introduction to Generics in Go | by Na'aman Hirschfeld
In this case the any type is correct — this function receives n number of slices of type T, which can be of...
Read more >
How to use type parameters for generic programming - JetBrains
All you need is to introduce the type parameter and change the function parameter in the signature. func PrintSlice[T any](s []T) ...
Read more >
How To Use Generics in Go | DigitalOcean
In programming, a generic type is a type that can be used in conjunction with ... you create a field called cards to...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found