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

时间:2017-03-02 15:41:55

标签: 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.

解决此问题的一种可能性是在"noImplicitAny"中将false设置为tsconfig.json。但这是我不想要的。我想知道什么不是类型问题。

所以我为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编译器识别我的类型声明文件但没有任何效果。

那我该怎么办?

1 个答案:

答案 0 :(得分:6)

你需要帮助编译器知道你写的内容是针对那个模块的。

试试这个:

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中。