【问题标题】:Declare a .d.ts file of a JS dependency that exports a function声明一个导出函数的 JS 依赖项的 .d.ts 文件
【发布时间】:2019-05-17 21:22:22
【问题描述】:

我在我的打字稿项目中使用了一个依赖项 (https://www.npmjs.com/package/is-class)。此依赖项没有 @types 定义,因此,到目前为止,我一直在使用带有 declare module 'is-class'; 的自定义 .d.ts 文件来进行导入。但是,我想为这个依赖添加类型。

is-class 基本上导出一个接收 1 个参数并返回布尔值的函数。我一直在尝试将此添加到我的 .d.ts 文件中,但到目前为止我尝试过的所有操作都会引发一个错误或另一个错误,到目前为止我最好的猜测是:

declare module 'is-class' {
    function isClass(a: any): boolean;
    export = isClass;
}

在我的 ts 代码中:

import * as isClass from 'is-class';
// ...
const foo = isClass(bar);

这会引发消息:This module can only be referenced with ECMAScript imports/exports by turning on the 'esModuleInterop' flag and referencing its default export.,但我不确定最好的方法是什么。

【问题讨论】:

    标签: node.js typescript


    【解决方案1】:

    我刚刚遇到了类似的问题。

    首先我更新了 tsconfig.json 以包含几个新选项:

    {
        "compilerOptions": {
            "allowSyntheticDefaultImports": true,
            "esModuleInterop": true,
        }
    }
    

    (这不是整个配置文件。我只是排除了以前已经存在的选项。)

    我将导入行更改为如下内容:

    import isClass from 'is-class';
    

    声明文件看起来基本上和你描述的一样:

    declare module 'is-class' {
        function isClass(a: any): boolean;
        export = isClass;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-10
      • 1970-01-01
      • 2017-05-31
      • 1970-01-01
      • 2020-11-22
      • 2018-12-20
      • 1970-01-01
      • 2018-10-27
      相关资源
      最近更新 更多