I would like to extend (in OOP terms) the built-in AudioContext class in TypeScript:
class LiveAudioContext extends AudioContext {
constructor() {
super();
}
public setPlaybackRate(rate: number) {
console.log(`Set rate to ${rate}.`);
}
}
This is valid TypeScript, accepted by both the compiler and IntelliSense. At runtime however, I get a TypeError
, for which Chrome adds the following error message as well:
var liveCtx = new LiveAudioContext();
Failed to construct 'AudioContext': Please use the 'new' operator, this DOM object constructor cannot be called as a function.
Fair enough, I know how it would be possible to solve the issue in the compiled Javascript output. However, having to manually fix an error caused by the compiler after each build is just unsuitable for production use.
How could I accomplish this extension correctly, so that it is functional in the compiled output as well, and off-the-shelf?
Edit: of course, creating a wrapper class that effectively redefines every single method and property works, but I find it to be smelling -- more like, stinking, and badly -- from an architectural point of view:
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);
}
...
}
I believe that the following question provides a good solution: How to handle warnings for proprietary/custom properties of built-in objects in TypeScript
Essentially you extend the existing interface, and apply your new methods directly on the browser's objects.