BeetleJuice BeetleJuice - 2 months ago 10
TypeScript Question

Typescript 2: how to add to existing interface or type?

In

typescript 2
, the
window
object is of type
Window
-- an interface.

My code makes use of
OfflineAudioContext
, a class accessible via the
window
object that typescript does not know about:

let offlineCtx = new window.OfflineAudioContext(2,44100*40,44100);
//TS Error: Property 'OfflineAudioContext' does not exist on type 'Window'


The code is transpiled and runs without problem, but I would like to get rid of this error. Is it possible to add to the
Window
type in a custom
d.ts
or to solve my issue some other way?

Answer

You can add declarations to existing types, that's covered in the Declaration Merging part of the docs.

In your case you can do:

type OfflineAudioContextConstructor {
    new (num1: number, num2: number, num3: number): OfflineAudioContext;
}

interface Window {
    OfflineAudioContext: OfflineAudioContextConstructor;
}
Comments