在打字稿模块中扩展全局类型(例如“Window") [英] Extending global types (e.g. "Window") inside a typescript module

查看:34
本文介绍了在打字稿模块中扩展全局类型(例如“Window")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您使用 typescript 编写,并且不使用模块,则可以扩展全局 Window 对象.例如,这会编译:

界面窗口{我的计数器:数字;}window.myCounter = window.myCounter ||0;++window.myCounter;函数 outputLoadingDetails() {console.log(`myCounter= ${window.myCounter}`)}

但是如果我在函数 outputLoadingDetails 前面加上 export 前缀,看起来我正在把这个文件转换成一个模块.现在,当我访问 window.myCounter 时出现编译器错误.

界面窗口{我的计数器:数字;}window.myCounter = window.myCounter ||0;//错误:属性 'MyCounter' 在类型 `Window` 上不存在++window.myCounter;//错误:属性 'MyCounter' 在类型 `Window` 上不存在导出函数 outputLoadingDetails() {console.log(`myCounter= ${window.myCounter}`)//错误:类型 `Window` 上不存在属性MyCounter"}

看来我的接口声明不再扩展全局 Window 类型.

我发现的一种解决方法是将接口声明放入一个单独的 *.d.ts 文件中,并从我的模块中引用它.

但现在我很好奇.有什么方法可以在模块代码中扩展 Window 接口?

解决方案

是的,你只需要将接口包装到全局声明中即可:

声明全局{界面窗口{我的计数器:数字;}}

<块引用>

可以使用 declare global 声明从模块扩展全局范围

更多信息 这里


** 确保将文件视为模块(具有 importexport 语句,如果没有 - 您可以添加空的 export {})

If you are writing in typescript, and are not using modules, it is possible to extend the global Window object. For example, this compiles:

interface Window {
    myCounter: number;
}

window.myCounter = window.myCounter || 0;
++window.myCounter;

function outputLoadingDetails() {
    console.log(`myCounter= ${window.myCounter}`)
}

But if I prefix the function outputLoadingDetails with export, it appears I am converting this file into a module. I now get a compiler error when I access window.myCounter.

interface Window {
    myCounter: number;
}

window.myCounter = window.myCounter || 0; // ERROR: property 'MyCounter' does not exist on type `Window`
++window.myCounter;                       // ERROR: property 'MyCounter' does not exist on type `Window`

export function outputLoadingDetails() {
    console.log(`myCounter= ${window.myCounter}`)  // ERROR: property 'MyCounter' does not exist on type `Window`
}

It appears my interface declaration is no longer extending the global Window type.

One workaround I've found is to put the interface declaration into a separate *.d.ts file, and reference this from my module.

But now I'm curious. Is there some way I can extend the Window interface within the module code?

解决方案

Yes, you just need to wrap the interface into global declaration:

declare global {
    interface Window {
        myCounter: number;
    }
}

Global scope can be augmented from modules using a declare global declarations

More info here


** Make sure the file is treated as a module (has import or export statement, if not - you can add empty export {})

这篇关于在打字稿模块中扩展全局类型(例如“Window")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆