声明窗口的typescript定义的正确方法
我试图在窗口对象中定义新类型,如声明窗口的typescript定义的正确方法,typescript,Typescript,我试图在窗口对象中定义新类型,如webkitAudioContext。我已经创建了一个名为window.d.ts的单独文件,并在其中添加了以下代码 interface Window { AudioContext: Constructable; webkitAudioContext: Constructable; } interface Constructable { new(); } 从另一个模块导入定义文件,如下所示 /// <reference path="
webkitAudioContext
。我已经创建了一个名为window.d.ts的单独文件,并在其中添加了以下代码
interface Window {
AudioContext: Constructable;
webkitAudioContext: Constructable;
}
interface Constructable {
new();
}
从另一个模块导入定义文件,如下所示
/// <reference path="./window.d.ts" />
let contextClass = window.AudioContext || window.webkitAudioContext;
let context = new contextClass();
declare module window {
export interface Window {
AudioContext: Constructable;
webkitAudioContext: Constructable;
}
interface Constructable {
new();
}
}
那就不行了。定义窗口定义的正确方法是什么?对于
AudioContext
和webkitAudioContext
已经存在社区编写的定义。
如果您不熟悉@types,您可以在短期内阅读更多关于它的内容,它包含许多库的定义(您甚至可以使用JQueryPromise
作为一种类型)。此外,还可以使用自定义定义创建
global.d.ts
文件,其中包含如下代码:
declare var myCustomLib: any;
let Ctx = window.AudioContext || (window as any).webkitAudioContext;
然后您应该将global.d.ts
添加到tsconfig.json
,这样编译器就会知道您的定义:
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"outDir": "./build"
},
"exclude": ["node_modules"],
"files": ["./src/globals"]
}
如果您在尝试访问不推荐的功能时遇到问题,您可以通过(…as any)
构造来访问它们,如下所示:
declare var myCustomLib: any;
let Ctx = window.AudioContext || (window as any).webkitAudioContext;
我希望其中一些技术能够帮助您。我认为您不能将窗口声明放在名称空间中,它将不再匹配默认提供的窗口类型。