What is the correct syntax for typing the state in a selector using ReduxToolkit and Typescript?

Imagine I am designing the following slice:

import { createSlice } from '@reduxjs/toolkit';

interface ThoughtListDisplayOptions {
  shouldShowCreateDate: boolean
}

interface DisplayOptions {
  thoughtsList: ThoughtListDisplayOptions
}

interface OptionsState {
  display: DisplayOptions
}

const initialState:OptionsState = {
  display: {
    thoughtsList: {
      shouldShowCreateDate: true
    }
  }
};

const optionsSlice = createSlice({
  name: 'options',
  initialState: initialState,
  reducers: {
    setThoughtListDisplayOptions: (state, action) => {
      state.display.thoughtsList = action.payload;
    }
  }
});

interface State {
  options: OptionsState
}

export const selectThoughtListDisplayOptions =  (state: State) =>  state.options.display.thoughtsList;

If I want my selector to have typing support for autocomplete and other features, what is the proper way to type the State? Should there be a central State interface, or is defining an interface specific to the slice sufficient?

Answer №1

Make sure to define the selector State as RootState when setting it up.

https://redux-toolkit.js.org/usage/usage-with-typescript#getting-the-state-type

import { combineReducers } from '@reduxjs/toolkit';
const rootReducer = combineReducers({});
export type RootState = ReturnType<typeof rootReducer>;

https://react-redux.js.org/using-react-redux/usage-with-typescript#typing-the-useselector-hook


// TypeScript infers type: (state: RootState) => boolean const selectIsOn =
(state: RootState) => state.isOn

// TypeScript infers `isOn` is a boolean const isOn = useSelector(selectIsOn)
const isOn = useSelector( (state: RootState) => state.isOn)

You can easily set up a typed useSelector function like this:

import { useSelector, TypedUseSelectorHook } from "react-redux";

export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are some effective methods for troubleshooting Vue.js computed properties and templates?

I am facing challenges with debugging in Vue.js, especially when it comes to debugging computed properties or data values in templates. Currently, I am using the IIFE method for debugging as shown in : <h2 dir="auto"> {{(function(){debugger;let ...

MUI version 5 with styled-components and ListItemButton: The specified property 'to'/'component' is not recognized

While transitioning from MUI v4 to v5, I encountered a hurdle: in v4, I utilized makeStyles(), but now aim to fully switch to styled(). Unfortunately, I am struggling to get Typescript to recognize a styled(ListItemButton)(...) with to= and component= attr ...

Classifying Union Types based on their distinct characteristics

There is a specific type with its own unique property (method) type Functions = { method: "connect", request: number, response: number, } | { method: "remove", request: string, response: string, } I aim to create a function that can handle inp ...

"Troubleshooting the issue of Angular's ng-selected not functioning properly within an edit

https://i.stack.imgur.com/ZpCmx.png https://i.stack.imgur.com/h3TA6.png TS Pincodes: Array<string> = []; Html <ng-select [items]="Pincodes" [searchable]="true" [multiple]="true" [(ngModel)]="updateZoneDetails ...

What is the method for invoking an outer class function from an inner function in JavaScript?

class Outer{ private outFunction(){ console.log("Okay!"); } public functionWeCall(){ function innerFunction(){ this.outFunction(); //That doesn't work } } } I am attempting to organiz ...

In React, the state's value will revert back to its initialState whenever a new value is assigned

My App component has a simple functionality where it controls the state of a value to display a header. By using an onClick function, I'm updating the isHeaderVisible value to True in the Home component when a logo is clicked and another route is take ...

Transform the IO type to an array of Either in functional programming with the fp-ts

Looking for assistance with implementing this in fp-ts. Can someone provide guidance? const $ = cheerio.load('some text'); const tests = $('table tr').get() .map(row => $(row).find('a')) .map(link => link.attr(&apos ...

Contrasts in the immutability strategies of Vuex and Redux

After exploring Vuex and noticing how simple it is to mutate states with mutation handlers using basic assignment, I am currently delving into redux. I have come to realize that redux emphasizes immutability, which can make coding a bit more verbose. This ...

How to Update the Dropdown Selection in Angular 10 Using Angular Material without Modifying the List of Selected Options?

Recently started learning Angular and facing some challenges in understanding a particular concept. I am looking to create a dropdown menu with a list of options to choose from. Once an item is selected, it should be abbreviated in the dropdown box. For e ...

Why is type assertion required for TS array mapping?

This particular piece of code is causing an error: function myFilter(debts:Map<string, number>) : Map<string, number>{ return new Map([...debts] .map(d => [d[0], Math.round(d[1] * 10) / 10]) // error .filter(d => d[1] != 0) ) ...

I am experiencing an issue with React Select where it does not seem to recognize the value I have

Forgive me if this question sounds naive, I am still relatively new to Reactjs, I kindly ask not to suggest using Hooks as they are not compatible with my current project. Currently, I am focusing on a form and its validation process. Here is the snippe ...

CDK Continuous Integration/Continuous Deployment pipeline encountering difficulties locating references within stack for deployment

My goal is to set up a cdk cicd pipeline for an app that already has a cdk stack and deploys successfully manually with cdk deploy. I want the cdk pipeline to automatically deploy the stack whenever changes are pushed to the main branch so that it's n ...

Personalized path-finding tree iterator

I am trying to implement a custom iterator in JavaScript that can traverse a DOM tree based on specific criteria provided by a callback function. The goal is to return an array of the nodes that match the criteria as the generator iterates through the tree ...

Combine the remaining bars by stacking the highest one on top in Highchart

Making use of stacking to display the highest value as the longest column/bar, with smaller values being merged within the highest one, can create a more visually appealing stack chart. For example, when looking at Arsenal with values of 14 and 3, ideally ...

Exceeded maximum stack size error encountered in Ionic 2 Tab bar functionality

When I attempt to incorporate a tab bar into my application, an error message saying "Maximum call stack size exceeded" is displayed Profile.html <ion-tabs> <ion-tab tabIcon="water" tabTitle="Water" ></ion-tab> <ion-tab tabI ...

Mapped Generics in Typescript allows you to manipulate and

Currently, I am attempting to utilize TypeScript generics in order to transform them into a new object structure. Essentially, my goal is to change: { key: { handler: () => string }, key2: { hander: () => number }, } to: ...

Using TypeScript to access the outer "this" from a literal getter

When attempting to access the outer "this" scope in Typescript while using getters and setters in object literals, it seems there is no straightforward method. Take for example the code snippet below: class Report { stuff: any[]; options = { ...

Is there a way for me to bypass adding the label if it already exists in my state, but still include the new value?

I am currently facing an issue with a dropdown select field where I can choose various attribute values. The problem arises when attempting to save the selected data in the state, as the label appears twice and I only require it once. My goal is to exclude ...

Testing a function that involves multiple HTTP requests through unit testing

I am struggling with writing a unit test for a function that indirectly triggers multiple HTTP requests. The service I am testing has the following structure: /* content.service.ts */ import { Injectable } from "@angular/core" import { ApiService } from ...

Encountering an error in a map operation does not hinder the subsequent map operation from being carried out

Within my angular application, I have implemented a Login method that performs the following tasks: login(username, password): Observable<User> { let data = new URLSearchParams(); data.append('username', username); data.append(' ...