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

jsf*_*jsf 5 import typescript vuex typescript-typings vuejs2

在我的TypeScript代码中,我想要包含一个没有打字的NPM JavaScript模块.

import createPersist = require('vuex-localstorage');
Run Code Online (Sandbox Code Playgroud)

因此编译器抱怨:

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.
Run Code Online (Sandbox Code Playgroud)

一种可能解决这一被设置"noImplicitAny"falsetsconfig.json.但这是我不想要的.我想知道什么不是typechecked了.

所以我写了一个最小类型声明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;
Run Code Online (Sandbox Code Playgroud)

但是我仍然有同样的错误.我尝试了几件事来让TypeScript编译器识别我的类型声明文件,但没有任何效果.

那我该怎么做?

Avi*_*dad 7

你需要帮助编译器知道你写的是该模块.

试试这个:

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;
}
Run Code Online (Sandbox Code Playgroud)

不要忘记确保此声明文件包含在tsconfig.json中.

  • @花生PeA 取决于你的设置,如果你的 `tsconfig.json` 中没有 `files:` 或 `include` 行,它会被默认包含。如果你有 `files` 或 `include`,那么只需添加本地声明文件的路径。 (2认同)