typescript - 为什么在这种情况下界面合并不起作用?

标签 typescript visual-studio-code

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

interface WebGL2RenderingContext {
    myExtension(): void
}

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

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

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

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

最佳答案

我在页面底部找到了答案here (感谢 jcalz)它谈到了“全局增强”。

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

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

export default {} //makes this a module

关于typescript - 为什么在这种情况下界面合并不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51035887/

相关文章:

http - 无法触发 Giraffe 中实现的 Web 请求

typescript - 如何配置 VSCode 以运行 Yarn 2(使用 PnP)驱动的 TypeScript

javascript - 容器对象的引用相等

javascript - 如何在 Angular 上动态显示所选行数据的总和?

javascript - 如何在类上实现类型?

python - 使用 anaconda 在 Visual Studio 代码上导入 matplotlib 的 pyplot 失败

visual-studio-code - Visual Studio Code 更改文件资源管理器托盘的字体大小?

typescript - JSON 模式的 anyOf 类型如何转换为 typescript ?

node.js - 如何包含 TypeScript Azure Function 的依赖项

android - json_extract for in android in flutter 不工作