为什么在这种情况下接口合并不起作用?

Chr*_*s_F 2 typescript visual-studio-code

我正在 Visual Studio Code 中编写一些 WebGL 代码(类型声明来自 npm 包 @types/webgl2)并且 typescript 似乎没有合并以下接口。

interface WebGL2RenderingContext {
    myExtension(): void
}

const gl: WebGL2RenderingContext = canvasElem.getContext("webgl2")
gl.myExtension() //getting a TS error saying 'myExtension' does not exist on type WebGL2RenderingContext
Run Code Online (Sandbox Code Playgroud)

谁能解释为什么这不起作用?

编辑:所以我可能应该包括extends WebGLRenderingContext,因为这WebGL2RenderingContext是定义接口的方式。但是,它仍然没有像我预期的那样工作。

interface WebGL2RenderingContext extends WebGLRenderingContext {
    myExtension(): void
}

const gl: WebGL2RenderingContext = canvasElem.getContext("webgl2")
gl.myExtension() //works
gl.createTexture() //works
gl.createVertexArray() //getting a TS error saying 'createVertexArray' does not exist on type WebGL2RenderingContext

//note: createTexture is present in WebGLRenderingContext while createVertexArray is only present in WebGL2RenderingContext
Run Code Online (Sandbox Code Playgroud)

Chr*_*s_F 7

我找到了答案,在页面的底部在这里(感谢jcalz)那里谈论“全球增强”。

declare global {
    interface WebGL2RenderingContext extends WebGLRenderingContext {
        myExtensionMethod(): void
    }
}

WebGL2RenderingContext.prototype.myExtensionMethod = function() {
    // todo: implement myExtensionMethod
}

export default {} //makes this a module
Run Code Online (Sandbox Code Playgroud)