gpt4 book ai didi

TypeScript:访问全局模块/命名空间中的类

转载 作者:搜寻专家 更新时间:2023-10-30 21:00:41 24 4
gpt4 key购买 nike

我有以下情况:

module MyModule {
export class Image {
...
}

var image = Image(); // returns an instance of MyModule.Image
}

但是,我想创建 HTMLImageElement 的实例,而不是 MyModule.Image。如何指定我要实例化驻留在全局模块/命名空间中的类?

谢谢!

最佳答案

有很多方法,但我建议以任何方式使用 document.createElement。例如:

var image = <HTMLImageElement>document.createElement('img');

您可以创建方便的函数或类来为您包装它。

例如,其他方法之一是在类定义之前创建对原始 Image 类的引用:

var ImageElement = Image;

...

export class Image {
...
}

var image = new ImageElement()

但是它不会被识别为 HTMLImageElement 实例,即没有适当的代码完成。

编辑:这是我的非工作尝试,以增加评论中提到的 Window 界面:

interface Window {
Image: new(width?: number, height?: number) => HTMLImageElement;
}

它编译正确(即没有错误),但在 Visual Studio 中它被标记为错误,提示 Duplicate Identifier 'Image',并尝试通过 new window.Image 创建实例() 被标记为 new expressions only valid on constructors。有趣的是,它在其他接口(interface)上运行良好,并且如前所述,它可以正确编译。

关于TypeScript:访问全局模块/命名空间中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12779035/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com