reduxjs / redux-toolkit

The official, opinionated, batteries-included toolset for efficient Redux development
https://redux-toolkit.js.org
MIT License
10.72k stars 1.17k forks source link

`Type error: The inferred type of 'configureStore' cannot be named without a reference to '@reduxjs/toolkit/node_modules/redux'. This is likely not portable. A type annotation is necessary.` #3962

Closed khteh closed 3 months ago

khteh commented 11 months ago

"@reduxjs/toolkit": "^2.0.1", eror:

import { configureStore, Middleware } from '@reduxjs/toolkit';
import { rootReducer } from './rootReducer'
const middlewares: Middleware[] = [];
// @link: https://redux.js.org/recipes/configuring-your-store#simplifying-setup-with-redux-toolkit
/*export const configureStore = (preloadedState = {}) => {
  const store = configureReduxStore({
    reducer: rootReducer,
    middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(middlewares),
    preloadedState,
  })

  if (process.env.NODE_ENV !== 'production' && module['hot']) {
    module['hot'].accept('./rootReducer', () => store.replaceReducer(rootReducer))
  }
  return store
}*/
const store = configureStore({
  reducer: rootReducer,
  middleware: (getDefaultMiddleware) =>
      getDefaultMiddleware().concat(middlewares),
});
export type AppDispatch = typeof store.dispatch;

export default store;
markerikson commented 11 months ago

This is likely related to your TS config settings. Can you post your entire tsconfig.json, or ideally the entire project repo?

khteh commented 11 months ago
{
  "exclude": [
    "node_modules",
    "**/node_modules/**"
  ],
  "include": [
    "src/**/*",
    "api/**/*",
    ".next/types/**/*.ts",
    "grpc/**/*",
    "middleware.ts"
  ],
  "extensions": [
    "ts",
    "tsx"
  ],
  "node-option": [
    "cypress",
    "experimental-specifier-resolution=node",
    "loader=ts-node/esm"
  ],
  "compilerOptions": {
    "allowJs": false,
    "allowSyntheticDefaultImports": true,
    "baseUrl": ".",
    "composite": true,
    "declaration": true,
    "emitDecoratorMetadata": true,
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "forceConsistentCasingInFileNames": true,
    "importHelpers": true,
    "incremental": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "lib": [
      "dom",
      "dom.iterable",
      "es2022"
    ],
    "module": "esnext",
    "moduleResolution": "node",
    "noEmit": true,
    "noEmitOnError": true,
    "noFallthroughCasesInSwitch": false,
    "noImplicitAny": false,
    "noImplicitOverride": true,
    "noImplicitReturns": false,
    "noPropertyAccessFromIndexSignature": false,
    "outDir": "dist",
    "resolveJsonModule": true,
    "rootDir": ".",
    "skipLibCheck": true,
    "sourceMap": true,
    "strict": true,
    "strictNullChecks": true,
    "strictPropertyInitialization": false,
    "target": "ES2022",
    "paths": {
      "@api/*": [
        "api/*"
      ]
    },
    "plugins": [
      {
        "name": "next"
      }
    ]
  }
}
smanwaring commented 11 months ago

Also seeing this issue after upgrading to both "react-redux": "^9.0.4" and "@reduxjs/toolkit": "^2.0.1"

thovden commented 10 months ago

I just upgraded to the latest versions, and get a complaints for references to redux-thunk:

The inferred type of 'configureStore' cannot be named without a reference to '@reduxjs/toolkit/node_modules/redux-thunk'. This is likely not portable. A type annotation is necessary.ts(2742)

If i never the middleware the error goes away, so that's where the issue is here:

    middleware: getDefaultMiddleware =>
      getDefaultMiddleware()
        .concat(...featureMiddleware)
        .concat(...middleware) as never,
  })

Note that if I just use the default middleware (not my additional middleware) the error is still there.

UPDATE: I found another use of redux-thunk in the project, and after I removed that the error went away. @khteh @smanwaring I would suggest removing redux as a direct dependency in your package.json if you have it.

I'm getting other errors, though, in RTK Query #3983

v1adko commented 10 months ago

My issue is if the same nature but due to redux type collision. Yarn hoisting is the culprit and we are using redux-logger. Removing redux-logger solves the issue.

yarn nohoist config did not help, but I suspect using pnpm that doesn't hoist will work.

For everyone encointering the issue doing 'yarn why' (or equivalent for your package manager) with the name of the package that is listed in your error helps point out what dependency is colliding.

pfdgithub commented 10 months ago

After I upgraded from @reduxjs/toolkit@1.9.7 to @reduxjs/toolkit@2.0.1, I got an error with the following code:

Type error: The inferred type of 'updateFeature' cannot be named without a reference to '../../../node_modules/@reduxjs/toolkit/dist/createAsyncThunk'. This is likely not portable. A type annotation is necessary. ts(2742)

import { createAsyncThunk } from "@reduxjs/toolkit";

export const updateFeature = createAsyncThunk(
  `${typePrefix}/updateFeature`,
  async () => {
    return {} as any;
  },
);
% npm list redux

├─┬ @reduxjs/toolkit@2.0.1
│ ├─┬ redux-thunk@3.1.0
│ │ └── redux@5.0.1 deduped
│ └── redux@5.0.1
└─┬ react-redux@9.0.4
  └── redux@5.0.1 deduped
npm list react-redux

├─┬ @reduxjs/toolkit@2.0.1
│ └── react-redux@9.0.4 deduped
└── react-redux@9.0.4
ppalladino commented 9 months ago

Any updates on this error?

skurgansky-sugarcrm commented 9 months ago

https://typescript.tv/errors/#ts2742 problem described here. it is related to exported values from module. If you add type annotation manually Issue goes away. Why TS doesn't infer this type itself .. no idea

chrishoage commented 9 months ago

We are also running into this error, and deeps specifically due to "declaration": true, being enabled while exporting anything which depends on the tyypes of store (like RootState which is required to be exported, not to mention needing to export store for dispatch and getState)

However, we are unable to disable this config as we create a package out of our redux store and wish to have types generated from it.

Both tsc, tsup (trying both rollup dts generator and the new api-extractor) produce these errors.

Installing redux-thunk and redux as direct dependencies using pnpm does not alleviate this problem

In the previous versions of RTK we had a similar problem with actions

'../../../node_modules/@reduxjs/toolkit/dist/createSlice'. This is likely not portable. A type annotation is necessary.ts(2742)

Caused by

export const accountActions = slice.actions;

Simply spreading the actions "fixed' it .

// Spread "fixes" TS2742 error
export const accountActions = { ...slice.actions };

This feels similar, but no such workarounds existed for the errors with store. Because we are unable to find workarounds for this (and trying to annotate with EnhancedStore is cumbersome to the point where it's impractical) we are unable to upgrade to RTK 2.0

chrishoage commented 9 months ago

Making this a separate comment so any interested parties will be notified of this.

I discovered that simply importing all types will fix most of these errors. The only one it won't fix is the actions one outlined in the above comment.

import type * as rtk from "@reduxjs/toolkit";

Including this in any file which gives you TS2742 errors when using "declaration": true in your TSConfig (or it gets added for you during type bundle generation) will help typescript get all the needed types in scope, and using import type should prevent all of RTK being included in your bundle.

Antignote commented 5 months ago

I recently ran into this problem as well, any updates on the issue?

The solution provided by @chrishoage worked for me, but is it the correct solution?

I'm developing a npm package and did follow the official documentation for nextjs / typescript and ran into this problem.

chrishoage commented 5 months ago

We ended up aborting our upgrade because the work-round I highlighted above didn't work in some cases. Ultimately some types were not exported and typescript couldn't reconcile this.

I did notice that Typescript 5.5 mentions this error in particular in an upcoming release. I have not tested to see if it helps this situation at all

https://devblogs.microsoft.com/typescript/announcing-typescript-5-5-beta/#consulting-packagejson-dependencies-for-declaration-file-generation

https://github.com/microsoft/TypeScript/issues/42873

markerikson commented 5 months ago

Sorry we haven't had time to look at this. Can folks post some full repo projects that show this happening?

Antignote commented 5 months ago

Sorry, I'm not able to publish the repo since it's a company repo where this issue occours. @chrishoage is your repo public even tho you aborted the upgrade?

Let me know if it would help if I could upload something else, like ts config or what else.

But the issue occurs for every file which exports any kind of function that has types tied to redux toolkit for me. The package is within a Nx monorepo

The error is only shown att compile time, I'm using tsc to compile the package

ryuujo1573 commented 5 months ago

Sorry we haven't had time to look at this. Can folks post some full repo projects that show this happening?

Hi, please let me provide a humble example of such use case: ryuujo1573/rtk-ts2742-demo

Thank you for your time!

aryaemami59 commented 5 months ago

@ryuujo1573 Thanks for the repro, I'm gonna take a look,

aryaemami59 commented 5 months ago

If anybody else has any examples of this please let me know, it doesn't have to be a repro, a code snippet should be fine.

Alletkla commented 4 months ago

If anybody else has any examples of this please let me know, it doesn't have to be a repro, a code snippet should be fine.

Hope it helps. Seems pretty basic to me:

Seems to be related to AsyncThunkConfig. Cause when i try to type manually: export const fetchAllTasksAsync: AsyncThunk<Task[], void, AsyncThunkConfig> = createAsyncThunk(..)

I cant import AsyncThunkConfig

Cannot find name 'AsyncThunkConfig'.ts(2304)

@reduxjs/toolkit: "^2.2.6" react-redux: "^9.1.2"

export const fetchAllTasksAsync = createAsyncThunk(
    "features/assessments/fetchAll",
    async () => {
        const taskList = (await axios.get<Task[]>(`${import.meta.env.VITE_DOMAIN}/v1/tasks/`)).data
        return taskList
    }
)
tsconfig:
{
  "compilerOptions": {
    "composite": true,
    "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
    "target": "ES2020",
    "useDefineForClassFields": true,
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "skipLibCheck": true,

    /* Bundler mode */
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "moduleDetection": "force",
    "noEmit": true,
    "jsx": "react-jsx",

    /* Linting */
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true
  },
  "include": ["src"]
}

getting:

Type error: The inferred type of 'fetchAllTasksAsync' cannot be named without a reference to '../../node_modules/@reduxjs/toolkit/dist/createAsyncThunk'. This is likely not portable. A type annotation is necessary. ts(2742)

would appreciate a fast fix :)

aryaemami59 commented 4 months ago

@Alletkla

Can you run this command and try again to see if it fixes the issue:

npm install https://pkg.csb.dev/reduxjs/redux-toolkit/commit/28afb060/@reduxjs/toolkit
Alletkla commented 4 months ago

Hey @aryaemami59,

Yeah rolled back to the commit from 3 days ago and it went away for createAsyncThunk and also for configureStore.

Hopefully this results in an PR fast :)

georgeiliadis91 commented 3 months ago

Hello, I cannot provide a repo for the reproduction due to corporate. But I was facing this error including some others. Where my createApi slices, had warnings about being undefined on my middleware.

Downgrading my TS version from 5.5.3 -> 5.4.5 got rid of the errors for me.

dasler-fw commented 3 months ago

Not sure if its the right solution, but the error is gone when i set a type to the "store" variable. Example:

Error when:

const store = configureStore({
  reducer: reducers,
});

Solution:

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

const store: Store = configureStore({
  reducer: reducers,
});
aryaemami59 commented 3 months ago

@georgeiliadis91 Can you at least share the code snippet that is causing the error? I just need to have a general idea of what function is being called and what types are being used.

@dasler-fw I would highly advise against doing that as it overrides all the type inference provided by TypeScript. Instead can you try running this in your CLI and see if it fixes the issue:

npm install https://pkg.csb.dev/reduxjs/redux-toolkit/commit/28afb060/@reduxjs/toolkit
dasler-fw commented 3 months ago

@georgeiliadis91 Can you at least share the code snippet that is causing the error? I just need to have a general idea of what function is being called and what types are being used.

@dasler-fw I would highly advise against doing that as it overrides all the type inference provided by TypeScript. Instead can you try running this in your CLI and see if it fixes the issue:

npm install https://pkg.csb.dev/reduxjs/redux-toolkit/commit/28afb060/@reduxjs/toolkit

that does not work. i see that there are no errors when i downgrade to 1.9.7 redux toolkit package.

PS. yes, my solution is overriding desribed store types

EskiMojo14 commented 3 months ago

@georgeiliadis91 we've noticed a few regressions introduced with TS 5.5, would appreciate you opening a separate issue with any non-type-portability errors found :) as Arya said, we need more detail such as the code experiencing the issue.

aryaemami59 commented 3 months ago

@dasler-fw could you share a little bit more? What's the error you're getting? And what does your tsconfig.json look like?

dasler-fw commented 3 months ago

My problem was the same as in the title of the issue.

Now i solved my problem with update "typescript": "4.7.4" to "5.5.3"

georgeiliadis91 commented 3 months ago

@georgeiliadis91 we've noticed a few regressions introduced with TS 5.5, would appreciate you opening a separate issue with any non-type-portability errors found :) as Arya said, we need more detail such as the code experiencing the issue.

Happy to provide some. But I cannot provide examples due to the code being internal enterprise

EskiMojo14 commented 3 months ago

sure, as long as you can make a minimal reproduction of the issue we can look into it all the same :)

ANPA21 commented 3 months ago

Instead can you try running this in your CLI and see if it fixes the issue:

npm install https://pkg.csb.dev/reduxjs/redux-toolkit/commit/28afb060/@reduxjs/toolkit

Had the same issue as abovementioned, with using RTK Query createApi. Exporting query hook resulted in TS error 2742.

"@reduxjs/toolkit" :"^2.2.6" "react-redux": "^9.1.2", "typescript": "^5.4.5",

Your suggested package fixed that issue

KingPr0f commented 3 months ago

Not sure if its the right solution, but the error is gone when i set a type to the "store" variable. Example:

Error when:

const store = configureStore({
  reducer: reducers,
});

Solution:

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

const store: Store = configureStore({
  reducer: reducers,
});

thnx. its solution for my case

markerikson commented 3 months ago

@KingPr0f , @dasler-fw : DO NOT DO THAT! That will remove all meaningful types from the store!

dasler-fw commented 3 months ago

@KingPr0f , @dasler-fw : DO NOT DO THAT! That will remove all meaningful types from the store!

Yes. thank you. I got it and changed my solution to just update ts to 5 vers.

markerikson commented 3 months ago

Fixed in https://github.com/reduxjs/redux-toolkit/releases/tag/v2.2.7 !

Hussein-Ali-6 commented 3 months ago

For anyone still experiencing the issue even after installing the latest versions of TypeScript and Redux, try exporting the initial state type. This should resolve the problem.

export interface AuthState { status: "idle" | "loading" | "succeeded" | "failed"; error: string | null; user: User | null; }