在我的 TypeScript 代码中,我想包含一个没有类型的 NPM JavaScript 模块。
import createPersist = require('vuex-localstorage');
因此编译器会提示:
error TS7016: Could not find a declaration file for module 'vuex-localstorage'. '<path>\node_modules\vuex-localstorage\dist\index.js' implicitly has an 'any' type.
解决此问题的一种可能性是在我的 tsconfig.json
中将 "noImplicitAny"
设置为 false
。但这是我不想要的。我想知道什么不再进行类型检查。
所以我为 vuex-localstorage
写了一个最小类型声明,放在我的项目目录中:
interface PersistOptions {
namespace?: string;
initialState?: any;
provider?: any;
serialize?: (data:any) => string;
deserialize?: (str:string) => any;
expires?: number;
merge?: (args:any[]) => any;
reducer?: (state:any, paths:string[]) => any;
paths?: string[];
}
declare function createPersist(options: PersistOptions): any;
export = createPersist;
但是我仍然有同样的错误。我尝试了几种方法让 TypeScript 编译器识别我的类型声明文件,但没有任何效果。
那我该怎么做呢?
最佳答案
您需要帮助编译器知道您为该模块编写的内容。
试试这个:
declare module 'vuex-localstorage' {
interface PersistOptions {
namespace?: string;
initialState?: any;
provider?: any;
serialize?: (data: any) => string;
deserialize?: (str: string) => any;
expires?: number;
merge?: (args: any[]) => any;
reducer?: (state: any, paths: string[]) => any;
paths?: string[];
}
function createPersist(options: PersistOptions): any;
export = createPersist;
}
不要忘记确保此声明文件包含在 tsconfig.json 中。
关于 typescript :如何为 npm 模块使用本地类型声明文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42559742/