我试图在窗口对象中定义新类型,比如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();
}
}那就没用了。定义窗口定义的正确方法是什么?
发布于 2016-12-09 09:03:09
已经存在针对AudioContext和webkitAudioContext 这里的社区书面定义。如果您不熟悉@type(您可以很快在这里上阅读更多),那么它包含了很多库的定义(甚至可以使用JQueryPromise作为类型)。
还有使用自定义定义创建global.d.ts文件的global.d.ts,它将包含如下代码:
declare var myCustomLib: any;然后您应该将global.d.ts添加到tsconfig.json中,这样编译器就会知道您的定义:
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"outDir": "./build"
},
"exclude": ["node_modules"],
"files": ["./src/globals"]
}如果您在尝试访问不推荐的特性时遇到了一些情况,您可以通过(... as any)构造来访问它们,如下所示:
let Ctx = window.AudioContext || (window as any).webkitAudioContext;我希望这些技巧能对你有所帮助。
https://stackoverflow.com/questions/41055871
复制相似问题