如何为将方法放在全局命名空间 (window) 上的库编写 Typescript 定义文件?

How to write a Typescript definition file for a library that puts methods on the global namespace (window)?

我正在使用依赖于 P5.js library.

的 Typescript 构建应用程序

P5.js 在全局命名空间上放置了很多函数,因此只需说 draw()ellipse(x, y, w, l) 等即可在您的 webapp 中调用它们...

我在 Webstorm 工作,我希望 Webstorm 能够为我执行静态分析,所以我一直在将 P5.js 的函数名称添加到 p5.d.ts 文件中(there is no p5.js Typescript 定义文件已发布),如:

declare var setup: () => void;
declare var draw: () => void;
declare var background: (color: number) => void;
declare var stroke: (r: number, g: number, b: number) => void;
...

然而这并不理想。

#1:这些函数实际上做了 return 一些事情——一个 P5 对象——它包含所有这些方法,尽管它通常不被使用。

#2:我仍然在整个应用程序中调用这些方法,没有任何前缀或任何东西。这使得这些函数的实际来源有点模糊。

还有更多问题...

任何人都可以提供一些关于如何为 P5.js 这样的库创建 .d.ts 的建议吗?

写成函数更自然。您还可以声明一个接口类型来表示常见的 return 类型(我假设他们将其设置为 "chaining" API?)

declare function stroke(r: number, g: number, b: number): P5;
declare function background(color: number): P5;

interface P5 {
  stroke(r: number, g: number, b: number): P5;
  background(color: number): P5;
}

不幸的是,在 TypeScript 中无法表达 "Make this part of the global scope at the same time",因此您必须复制这些定义。

关于#2,嗯,那是P5的问题?我会看看 P5 文档是否提供了一种更智能的调用函数的方法。将一堆东西放在全局范围内不再是 JS 库的常见模式,因此可能还有其他方法可以做到这一点。

更新

显然是 there is another way to use P5.js functions without polluting the global namespace