为缺失的方法添加类型(来自 npm 包)

add typings for missing method (from a npm package)

我正在使用包 @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 Repo 的类型可以是 found on github(它看起来很相似,但太大而无法在此处显示)

以下是我在 angular 组件中导入 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

中 fiddle

P.S。 我已经在 github 上打开了一个关于更新定义的问题(没有拉取请求,因为当时几乎不了解 git)。

据我所知,你不能在打字稿中做到这一点。 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;
}

选角总是丑陋的,但至少你把它隐藏在一个地方,我认为这是合理的...

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

看到并阅读(参见 Aviad Hadad 的回答)class 合并是不可能的并阅读 typescripts node module resolution 基本上,如果您导入像 import * as Cropper from 'cropperjs 这样的非相对路径,typescript 将在名为 node_modules 的文件夹中查找适当的文件,并从包含 import 语句的文件所在的目录开始。然后向上遍历(取自打字稿文档的例子)

  • /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 目录,一切仍然有效。 缺点是你必须复制和粘贴代码。