如何将 redux-persist 添加到 typescript 项目?

How to add redux-persist to typescript project?

我正在尝试将 redux-persist 添加到我的 React 项目中(使用打字稿)。但是我有点麻烦。编译失败并出现以下错误:

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'

我安装了以下软件包:“@types/redux-persist”:“^4.3.1”和"redux-persist":“^6.0.0”。

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";
}

如何解决这个问题?

解法:

添加这一行:

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

react-app-env.d.ts 如果你使用 create-react-app.

解释:

打字稿中的三斜杠指令 是包含单个 XML 标记的单行注释。注释内容用作编译指令.

这些指令用于声明对包的依赖,可以是类型、库、路径等。

解析这些包名称的过程类似于在导入语句中解析模块名称的过程。将 三斜杠引用类型 指令视为声明包的 import 的一种简单方法。

例如,在上面的代码中,在声明文件中包含 /// <reference types="redux-persist" /> 声明该文件使用在 @types/node/redux-persist.d.ts[= 中声明的名称43=];因此,这个包需要与声明文件.

一起包含在编译

阅读更多here

解决方案:

从 'redux-persist/es/storage' 导入存储而不是从 'redux-persist/lib/storage'

导入存储