【问题标题】:add typings for missing method (from a npm package)为缺少的方法添加类型(来自 npm 包)
【发布时间】:2017-11-08 13:11:42
【问题描述】:

我正在使用包@types/cropperjs 不幸的是,它落后于当前的cropper.js 版本并且缺少scale 方法。 到目前为止,我只是手动将缺失的方法添加到 node_modules 下的 d.ts 文件中(这显然是个坏主意,所以不要这样做!这只是一个临时修复)

我尝试将来自 node_modules 的定义与我自己的声明合并。

declare class cropperjs {

  /**
   * Scale the image.
   *
   * @param scaleX The scaling factor to apply on the abscissa of the image.
   * When equal to 1 it does nothing. Default is 1
   * @param scaleY The scaling factor to apply on the ordinate of the image.
   * If not present, its default value is scaleX.
   */
   scale(scaleX: number, scaleY?: number): void;
}

export = cropperjs;
export as namespace Cropper;

来自 DefinitlyTyped 存储库的类型可以是 found on github(看起来很相似,但太大而无法在此处显示)

以下是我在角度组件中导入cropper 的方法。

import * as Cropper from 'cropperjs';

这是我的 tsconfig.json(部分内容)

 "typeRoots": [
  "node_modules/@types",
  "node_modules/@angular",
  "src/typings"
],
"types": [
  "jasmine",
  "node",
  "karma",
  "webpack",
   "cropperjs" 
]

我用我的自定义类型文件夹和三斜杠引用符号尝试了它。 但我不知道如何成功合并我的定义和 DefinitlyTyped 的定义,这样我就可以使用cropperjs 而不必在 node_module 中摆弄

附: 我已经在 github 上打开了更新定义的问题(没有拉取请求,因为当时几乎不了解 git)。

【问题讨论】:

    标签: angular typescript typescript-typings


    【解决方案1】:

    据我所知,你不能在打字稿中做到这一点。 Typescript 有声明合并的概念,这让我们可以扩展其他人编写的类型,您可以合并接口和命名空间,但不能合并类。看here。

    如果 @types/cropperjs 是使用接口编写的,您可以使用自己的声明扩展该接口。

    这是你现在可以做的一个丑陋的黑客攻击:

    import * as Cropper from 'cropperjs';
    
    interface MyCropper extends Cropper {
      scale(scaleX: number, scaleY?: number): void;
    }
    
    function CreateCropper(dom: HTMLImageElement, options: Cropper.CropperOptions): MyCropper {
      return new Cropper(dom, options) as MyCropper;
    }
    

    选角总是丑陋的,但至少你把它藏在一个地方,我觉得还是合理的……

    【讨论】:

      【解决方案2】:

      只是想添加另一个可能的“解决方案”。我说“解决方案”是因为在我看来它很丑陋,但又是一种解决方法。

      在查看和阅读(请参阅 Aviad Hadad 的回答)后,无法进行类合并并阅读了 typescripts node module resolution 基本上,如果您导入像 import * as Cropper from 'cropperjs 这样的非相对路径,typescript 将在名为 node_modules 的文件夹中查找适当的文件,并且它从具有 import 语句的文件所在的目录开始。然后它向上遍历(示例取自 typescript 文档)

      • /root/src/node_modules/moduleB.ts
      • /root/node_modules/moduleB.ts
      • /node_modules/moduleB.ts(我假设这是全局 node_modules 目录)

      由于 typescript 还会查找 d.ts 文件,因此我从 @types/cropperjs 包中复制了整个 index.d.ts,将其重命名为 cropperjs.d.ts 并将其放在名为 /root/src/node_modules 的文件夹中。 (并添加了缺失的方法)

      如果您使用tsc --traceResolution 跟踪分辨率,您会看到打字稿将从自定义node_modules 目录中获取d.ts 文件。

      此解决方案的优点是您不必接触您的代码。只要@types/cropperjs 更新了缺失的方法,您就可以删除您的自定义 node_modules 目录,一切仍然有效。 缺点是你必须复制和粘贴代码。

      【讨论】:

        猜你喜欢
        • 2016-07-27
        • 1970-01-01
        • 1970-01-01
        • 2022-11-11
        • 2018-11-10
        • 2019-12-20
        • 2015-01-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多