WebGL - 如何在 Typescript 中正确地将程序参数传递给 gl.attachShader?

WebGL - How to pass program parameter to gl.attachShader correctly in Typescript?

我创建了这样一个程序:

const program: WebGLProgram = gl.createProgram();

然后最终尝试将着色器附加到程序,如下所示:

gl.attachShader(program, vertexShader);

这将引发以下错误:

Error: TypeError: Failed to execute 'attachShader' on 'WebGL2RenderingContext': parameter 1 is not of type 'WebGLProgram'.

观察程序,typeof program等于object,所以错误是有道理的。

如果我尝试执行以下操作,如果我将程序类型更改为 any,这会起作用,因为 typeof program.program 等于 WebGLProgram:

gl.attachShader(program.program, vertexShader);

它会抛出以下错误:

Property 'program' does not exist on type 'WebGLProgram'.

在 Typescript 中解决这个问题的正确方法是什么?我不想用 any 类型写 program.program

这个错误不是TypeScript编译器抛出的,是浏览器运行时抛出的。如果tsconfig.json compilerOptions中启用了strictNullChecks,你会看到WebGLRenderingContext/createProgram的return类型是WebGLProgram | null,那么你必须先检查program 不为空:

const canvas = document.createElement("canvas");
const gl = canvas.getContext("webgl");
if (gl) {
  const program = gl.createProgram();
  const vertexShader = gl.createShader(gl.VERTEX_SHADER);
  if (program && vertexShader) {
    gl.attachShader(program, vertexShader);
  } else {
    throw new Error("WebGL createProgram or createShader failed!");
  }
} else {
  throw new Error("WebGL seems not supported!");
}

TypeScript Playground