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

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 opened this issue Dec 8, 2023 · 35 comments

Comments

@khteh
Copy link

khteh commented Dec 8, 2023

"@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
Copy link
Collaborator

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

@khteh
Copy link
Author

khteh commented Dec 8, 2023

{
  "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
Copy link

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

@thovden
Copy link

thovden commented Dec 16, 2023

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
Copy link

v1adko commented Dec 16, 2023

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
Copy link

After I upgraded from @reduxjs/[email protected] to @reduxjs/[email protected], 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/[email protected]
│ ├─┬ [email protected]
│ │ └── [email protected] deduped
│ └── [email protected]
└─┬ [email protected]
  └── [email protected] deduped
npm list react-redux

├─┬ @reduxjs/[email protected]
│ └── [email protected] deduped
└── [email protected]

@ppalladino
Copy link

Any updates on this error?

@skurgansky-sugarcrm
Copy link

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
Copy link

chrishoage commented Feb 9, 2024

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
Copy link

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
Copy link
Contributor

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
Copy link

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

microsoft/TypeScript#42873

@markerikson
Copy link
Collaborator

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

@Antignote
Copy link
Contributor

Antignote commented May 25, 2024

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
Copy link

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
Copy link
Contributor

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

aryaemami59 added a commit to aryaemami59/redux-toolkit that referenced this issue Jun 8, 2024
- This should serve as a partial fix for reduxjs#3962, reduxjs#4448, reduxjs#3983, reduxjs#4066, reduxjs#4108, reduxjs#4401
- Here is the list of the problematic (now exported) types:
  From `@reduxjs/toolkit`:
  - `CombinedSliceReducer`
  - `CaseReducerDefinition`
  - `Id` renamed to `TSHelpersId`
  - `UncheckedIndexedAccess`
  - `ReducerWithInitialState`
  - `CaseReducerDefinition`
  - `Id` renamed to `TSHelpersId`
  - `UncheckedIndexedAccess`
  - `ReducerWithInitialState`
  From `@reduxjs/toolkit/query/react`:
  - `UseLazyQuery`
  - `UseQuery`
  - `QueryHooks`
@aryaemami59
Copy link
Contributor

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
Copy link

Alletkla commented Jul 6, 2024

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
Copy link
Contributor

aryaemami59 commented Jul 9, 2024

@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
Copy link

Alletkla commented Jul 9, 2024

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
Copy link

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
Copy link

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
Copy link
Contributor

@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

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