为什么在这种情况下接口合并不起作用? [英] Why is interface merging not working in this case?
问题描述
我正在 Visual Studio Code 中编写一些 WebGL 代码(类型声明来自 npm 包 @types/webgl2)并且 typescript 似乎没有合并以下接口.
I'm writing some WebGL code in Visual Studio Code (with type declarations coming from npm package @types/webgl2) and typescript doesn't seem to be merging the following 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
谁能解释为什么这不起作用?
Can anyone explain why this doesn't work?
所以我可能应该包括 extends WebGLRenderingContext
,因为这是定义 WebGL2RenderingContext
接口的方式.但是,它仍然没有像我预期的那样工作.
So I probably should have included extends WebGLRenderingContext
, as this is how the interface of WebGL2RenderingContext
is defined. However, it still does not work as I was expecting.
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
推荐答案
我在页面底部找到了答案此处(感谢 jcalz)在那里讨论了全局增强".
I found the answer at the bottom of the page here (thanks jcalz) where it talks about "global augmentation".
declare global {
interface WebGL2RenderingContext extends WebGLRenderingContext {
myExtensionMethod(): void
}
}
WebGL2RenderingContext.prototype.myExtensionMethod = function() {
// todo: implement myExtensionMethod
}
export default {} //makes this a module
这篇关于为什么在这种情况下接口合并不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!