Exploring the proper way to infer generic types for Redux Toolkit Slices

I've been working on a function that takes a slice factory as an argument and performs some operations on it. However, I'm facing challenges in setting up the types correctly.

Below is a simple example showcasing the issue:

Slice factory:

export default function sliceFactory() {
    return createSlice({
        name: "addExercise",
        initialState: {
            query: "",
        },
        reducers: {
            startSearch(state) {
                state.query = "";
            },
            changeQuery(state, action) {
                state.query = action.payload;
            },
        },     
    });
}

The sliceFactory function's type appears to be inferred correctly using:

type Test1 = typeof sliceFactory;
==> () => Slice<{
        query: string;
        }, {
            startSearch(state: WritableDraft<{query: string;}>): void;
            changeQuery(state: WritableDraft<{query: string;}>, 
                action: { payload: any; type: string;}): void;
        }, "addExercise">

Utility function:

function checkType<
    TState,
    TCaseReducers extends SliceCaseReducers<TState>,
    TName extends string,
    TSliceFactory extends () => Slice<TState, TCaseReducers, TName>,
>(sliceFactory: TSliceFactory) {
    return sliceFactory;
}

I anticipate being able to pass sliceFactory into the utility function and have the types inferred accurately

const result = checkType(sliceFactory); 
type Test2 = typeof result ==> ideally, the same as before

Instead, what I received was:

type Test2 ==> () => Slice<unknown, SliceCaseReducers<unknown>, string>

Along with the familiar error message:

Argument of type '() => Slice<{ query: string; }, { startSearch(state: WritableDraft<{ query: string; }>): void; changeQuery(state: WritableDraft<{ query: string; }>, action: { payload: any; type: string; }): void; }, "addExercise">' 
is not assignable to parameter of type '() => Slice<unknown, SliceCaseReducers<unknown>, string>'.

What am I overlooking? Appreciate your help!

Answer №1

Appreciation to 0xts for the valuable contribution. I ultimately implemented the following solution:

function verifyType<
  TStoreFactory extends () => Slice<
    any,
    any,
    any
  >
>(sliceFactory: TSliceFactory) {
  // [ ... ] perform actions with sliceFactory
  return sliceFactory; // sender will get factory accurately typed
}

   

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

Encountering a 404 error when trying to retrieve the Next.js 14 API route, despite specifying the use of route

Currently, I am working with Next.js version 14.2.3 and attempting to access the /api/tmp API route from the chat.tsx component. However, I keep encountering a 404 error even though I am using the route.ts file. What could be causing this issue? UPDATE: C ...

Avoid accessing invariant variables when mocking: __extends

I'm currently in the process of converting a collection of react components from JavaScript to TypeScript, and I've encountered an issue with jest.mock(). Before: "react": "^15.6.1" "jest": "20.0.4" "enzyme": "^2.9.1" CustomDate.js ... import ...

Intellisense missing in VSCode for Angular and typings

Attempting to start a new project using Angular 1.5.5 and looking to incorporate TypeScript into my coding process within Visual Studio Code. I have included the necessary typings for Angular in my project: typings install angular --save --ambient I&ap ...

Express TypeScript Error Handling Function

What are the different data types for the four parameters used in the error handling function in Typescript? app.use((err: ??, req: ??, res: ??, next: ??) => { }); While working in VS Code, I noticed red wiggly lines under all four parameters without ...

XState: linking together multiple promises seamlessly without needing intermediate states

After reading the Invoking Multiple Services section, it seems that despite being able to invoke multiple promises, they appear to be triggered without waiting for the previous one to complete in my own tests. // ... invoke: [ { id: 'service1' ...

Error TS7053 indicates that an element is implicitly assigned the 'any' type when trying to use a 'string' type to index a 'User_Economy' type

Struggling with a particular question, but can't seem to find a solution. Error: TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'User_Economy'. No ind ...

How can this be happening? It's expected that items will be printed, but for some reason

I'm struggling to figure out why the console.logs aren't showing up. import { GenericRepository, getGenericRepository } from '../src/database/repository/GenericRepository'; import { start, stop } from '../src/index'; import r ...

Tips for transmitting data from Dart to Typescript Cloud functions, encountering the UNAUTHENTICATED error code

Snippet of Dart code with token passed to sendToDevice: Future<void> _sendNotification() async { CloudFunctions functions = CloudFunctions.instance; HttpsCallable callable = functions.getHttpsCallable(functionName: "sendToDevice"); callable.c ...

RC6 - What is the significance of encountering an 'Unexpected token <' error message?

After updating to RC.6, I am encountering a series of errors related to third-party components. Specifically, the error message displayed is: SyntaxError: Unexpected token <. This issue has arisen with ng2-bootstrap, ng2-select, and angular2-jwt. Howev ...

Redux - a method of updating state through actions

Hello, I am currently working on developing a lottery system and I have a question regarding the best approach to modify state using action payloads. Let's consider the initial state: type initialCartState = { productsFromPreviousSession: Product[ ...

Inspecting a union type with a TypeScript property validation

I have defined a union of two types in my code. Here are the definitions: type Generic = { subtype: undefined, user: string, text: string } type Other = { subtype:'message', text: string } type Message = Generic | Other; Within my co ...

Arrange an array of integers and letters alphabetically in an Angular/Typescript environment

My Sorting Strategy I am attempting to organize an array in the following manner... 1 2 2(a) 2(b) 2(b) #AsimpleName 2(b) #NameWithN 3 4 4(a) ... ... using Angular 2. Snippet of My Code Component this.streetDetailRef = this.afDatabase.list('data/us ...

What are the different ways to customize the appearance of embedded Power BI reports?

Recently, I developed a website that integrates PowerBI embedded features. For the mobile version of the site, I am working on adjusting the layout to center the reports with a margin-left style. Below are the configuration parameters I have set up: set ...

Ways to prevent a user from reaching a specific page by entering the URL in a react and typescript application

Is there a way to restrict access to a specific page with the URL "myurl/view"? I want only admin users to be able to view this page, while preventing other users from accessing it. Currently, when the view button is clicked, it redirects to the URL "/vie ...

The world of TypeScript generics and derived data types

I'm looking to streamline the process of calling multiple functions by creating a function that handles this task. These functions all require similar business logic and cleanup operations. function foo(arg: number) { // perform actions using arg ...

Angular 5 Image Upload - Transfer your images with ease

I am having trouble saving a simple post in firebase, especially with the image included. This is my current service implementation: uploadAndSave(item: any) { let post = { $key: item.key, title: item.title, description: item.description, url: '&a ...

Jest: A runtime error occurred because the property being accessed is undefined

Currently, I am testing my React class which includes the import statement import dotnetify from "dotnetify";. While this works without any issues, Jest is reporting that dotnetify is undefined. Interestingly, when I switch the import to const do ...

Convert image file to a React TypeScript module for export

Imagine a scenario where you have a folder containing an image file and an index file serving as a public API. Is there a method to rename the image file before reexporting it? Here is the structure of the folder: └── assets/ ├── index.t ...

What is the process for transforming a multi-dimensional array containing strings into a multi-dimensional array containing numbers?

I've got a unique structure of data composed of arrays with strings as seen below: [ 0: Array(1) 0: Array(6) 0: [5.379856, 43.252967] 1: [5.422988, 43.249466] 2: [5.425048, 43.245153] 3: [5.383804, 43.239 ...

Simple steps to transform the "inputs" syntax into the "@Input" property decorator

There's this code snippet that I need to modify: @Component({ selector: 'control-messages', inputs: ['controlName: control'], template: `<div *ngIf="errorMessage !== null">{{errorMessage}}</div>` }) Is the ...