在 TypeScript 中扩展 AudioContext
Extend AudioContext in TypeScript
我想扩展(在 OOP 术语中)TypeScript 中的内置 AudioContext class:
class LiveAudioContext extends AudioContext {
constructor() {
super();
}
public setPlaybackRate(rate: number) {
console.log(`Set rate to ${rate}.`);
}
}
这是有效的 TypeScript,被编译器和 IntelliSense 接受。然而,在运行时,我得到一个 TypeError
,Chrome 也为此添加了以下错误消息:
var liveCtx = new LiveAudioContext();
Failed to construct 'AudioContext': Please use the 'new' operator, this DOM object constructor cannot be called as a function.
很公平,我知道如何解决 compiled Javascript output 中的问题。但是,每次构建后都必须手动修复由编译器引起的错误,这不适合生产使用。
我怎样才能正确地完成这个扩展,以便它在编译后的输出中也能正常工作?
编辑:当然,创建一个包装器 class 可以有效地重新定义每个方法并且 属性 可以工作,但我发现它有异味 - 更像是 发臭,而且很糟糕——从架构的角度来看:
class LiveAudioContext {
private internalContext: AudioContext;
public createBuffer() {
return this.internalContext.createBuffer.apply(this.internalContext, arguments);
}
public createBufferSource() {
return this.internalContext.createBufferSource.apply(this.internalContext, arguments);
}
...
}
我相信以下问题提供了一个很好的解决方案:How to handle warnings for proprietary/custom properties of built-in objects in TypeScript
本质上,您扩展了现有接口,并将新方法直接应用于浏览器的对象。
我想扩展(在 OOP 术语中)TypeScript 中的内置 AudioContext class:
class LiveAudioContext extends AudioContext {
constructor() {
super();
}
public setPlaybackRate(rate: number) {
console.log(`Set rate to ${rate}.`);
}
}
这是有效的 TypeScript,被编译器和 IntelliSense 接受。然而,在运行时,我得到一个 TypeError
,Chrome 也为此添加了以下错误消息:
var liveCtx = new LiveAudioContext();
Failed to construct 'AudioContext': Please use the 'new' operator, this DOM object constructor cannot be called as a function.
很公平,我知道如何解决 compiled Javascript output 中的问题。但是,每次构建后都必须手动修复由编译器引起的错误,这不适合生产使用。
我怎样才能正确地完成这个扩展,以便它在编译后的输出中也能正常工作?
编辑:当然,创建一个包装器 class 可以有效地重新定义每个方法并且 属性 可以工作,但我发现它有异味 - 更像是 发臭,而且很糟糕——从架构的角度来看:
class LiveAudioContext {
private internalContext: AudioContext;
public createBuffer() {
return this.internalContext.createBuffer.apply(this.internalContext, arguments);
}
public createBufferSource() {
return this.internalContext.createBufferSource.apply(this.internalContext, arguments);
}
...
}
我相信以下问题提供了一个很好的解决方案:How to handle warnings for proprietary/custom properties of built-in objects in TypeScript
本质上,您扩展了现有接口,并将新方法直接应用于浏览器的对象。