typescript :如何为 npm 模块使用本地类型声明文件

标签 typescript import vuejs2 typescript-typings vuex

在我的 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/

相关文章:

javascript - 输入验证 : change default error message

javascript - 如何在vuejs中设置cookie?

javascript - Typescript - 如何避免未声明对象的编译错误

html - 如何通过调整大小功能使 ag 网格标题具有粘性和响应性

class - TypeScript - 将类存储为 map 值?

reactjs - redux 工具包使用 typescript 模拟商店

python - 从 Python 到 Mathematica 再返回

python - 当文件名包含句点时如何引用python包

web-scraping - 试图在谷歌表格中获取加密货币价格数据,而没有像我们 SNX 这样的常见硬币

javascript - 父组件 vue 未接收到事件