我正在 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
谁能解释为什么这不起作用?
EDIT:所以我可能应该包括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
我在页面底部找到了答案here https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation(感谢 jcalz)其中谈到“全局增强”。
declare global {
interface WebGL2RenderingContext extends WebGLRenderingContext {
myExtensionMethod(): void
}
}
WebGL2RenderingContext.prototype.myExtensionMethod = function() {
// todo: implement myExtensionMethod
}
export default {} //makes this a module
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)