如何将模块中的 class 暴露给 TypeScript 中的全局命名空间?

How do you expose class in a module to the global namespace in TypeScript?

问题

给定

我试过的

我在global.d.ts

周围尝试了很多东西

例如

import gammaAlias from "../scripts/gamma";
export as namespace NS_Global;

declare global {
    var qqq: {n:string};
    namespace ZZZ {
       export var gamma: gammaAlias;
    }
    var gamma: gammaAlias;
}

但是 none 有效

即TypeScript 告诉我以下内容之一

github

I have a github repo set up to investigate these questions. https://github.com/penguin020/expose-typescript-modules-globally

ConvertToModulesPOC_original is the working "before" case.

ConvertToModulesPOC is a broken attempt to convert gamma .ts to a module and expose it globally.

PS

问题仍然存在,如何将模块暴露给全局命名空间?

任何使用 github 中示例的答案将不胜感激!

我在“TypeScript: exposing module types in the global context and why to avoid it”中找到了答案;

我已经更新了 github 存储库。

我发现的最显着的变化是:


tsconfig:

"module": "system",

yMod.ts

import gammaAlias from "../scripts/gamma.js";

declare global {
    export type gamma = gammaAlias;
    export const gamma: typeof gammaAlias;
}

(window as any).gamma = gammaAlias;

注意:您可以在另一个文件中包含全局环境声明,甚至是 *.d.ts 文件。


link above 分解了 每个要公开的符号有三个引用 的原因。那个页面上解释的很好,所以我只在这里总结一下:

  1. 将 class type 暴露给 TypeScript 编译器(不生成代码)
  2. 将 class 对象 公开给 TypeScript 编译器(所以有一个对象可以调用 new ;没有代码生成)
  3. 扩展 window 对象以在全局命名空间中公开 class(生成代码)。

希望我正确理解了你的问题。您希望将 'gamma' 暴露给全局命名空间,以便您可以直接从 'window' 还是来自控制台?

将以下两行添加到 class 底部的 gamma.ts 中。

let g = new gamma();
(window as any).gamma = g

1) 第一行初始化一个新的Gamma class 到变量g.

2) 第二行将g导出到全局命名空间,这样就可以从'window.g'调用或者只是'g'。

Screenshot

拉取请求 #1:https://github.com/penguin020/expose-typescript-modules-globally/pull/1/files


我还建议将这两行代码移动到您的主初始化文件'app.js'。

gamma.ts

export default class gamma {

app.ts

import gamma from "./gamma";
let g = new gamma();
(window as any).gamma = g

拉取请求#2:https://github.com/penguin020/expose-typescript-modules-globally/pull/2

这对我有用。我只希望我不必重命名界面。

declare global {
  interface IMyClass extends MyClass { }
}

class MyClass {

}

declare global {
  type IMyClass = MyClass;
}

class MyClass {

}