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

Typescript: How to use local type declaration file for npm module

在我的 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 中。