Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add redux-persist to typescript project?

I'm trying to add redux-persist to my React project (using typescript). But I have some trouble. Compiling falls with following error:

Could not find a declaration file for module 'redux-persist/lib/storage'. '.../WebstormProjects/catalog/node_modules/redux-persist/lib/storage/index.js' implicitly has an 'any' type.
  Try `npm install @types/redux-persist` if it exists or add a new declaration (.d.ts) file containing `declare module 'redux-persist/lib/storage'

I installed the following packages: "@types/redux-persist": "^4.3.1" and "redux-persist": "^6.0.0".

Content of redux-persist/lib/storage:

declare module "redux-persist/es/storage" {
  import { WebStorage } from "redux-persist/es/types";

  const localStorage: WebStorage;
  export default localStorage;
}

declare module "redux-persist/lib/storage" {
  export * from "redux-persist/es/storage";
  export { default } from "redux-persist/es/storage";
}

What to do to solve this problem?

like image 800
Слава Иванов Avatar asked Jan 23 '20 09:01

Слава Иванов


People also ask

How do I add redux persist?

Installation for redux persist:import { persistStore, persistReducer } from 'redux-persist'; For persistReducer is wrap your app's root reducers and pass it to the persistStore function it ensures your redux state is stored to persisted storage whenever it changes.

Can we use redux with TypeScript?

As of React-Redux v8, React-Redux is fully written in TypeScript, and the types are included in the published package. The types also export some helpers to make it easier to write typesafe interfaces between your Redux store and your React components.

Is it good to use redux persist?

With the Redux Persist library, developers can save the Redux store in persistent storage, for example, the local storage. Therefore, even after refreshing the browser, the site state will still be preserved.


1 Answers

Solution:

Add this line:

/// <reference types="redux-persist" />

to react-app-env.d.ts if your using create-react-app.

Explanatation:

Triple-slash directives in typescript are single-line comments containing a single XML tag. The contents of the comment are used as compiler directives.

These directives are utilised to declare a dependency on a package, which could be type, lib, path, etc..

The process of resolving these package names is similar to the process of resolving module names in an import statement. An easy way to think of triple-slash-reference-types directives are as an import for declaration packages.

For instance, in the code above, including /// <reference types="redux-persist" /> in a declaration file declares that this file uses names declared in @types/node/redux-persist.d.ts; and thus, this package needs to be included in the compilation along with the declaration file.

Read more here.

like image 52
Pouya Ataei Avatar answered Oct 19 '22 01:10

Pouya Ataei