Use our Code #5: A Little Typing can Save a Lot of Typing
Our team is developing a new WebGL enigne for this jam. In the process, I kept running in to cases where I wanted to check types, to provide helpful error messages if a complex data structure was mis-assembled by a caller. The ultimate solution to this problem is to use something like TypeScript, but since we wanted to use pure JS for familiarity's sake, it seemed like a good idea to write a typechecking helper. Hopefully, this can save you a little time in your own project.
The following routine takes object specifications like this:
javascript
const SHAPE = {
name: "string",
shader: "?object",
uniforms: "?object",
draw: "function",
}
The check can be performed with a simple call, which returns a boolean:
javascript
const is_good = shapeCheck(
x, // the untrusted object
SHAPE, // the type schema
);
It supports nullability with the ? prefix, but it does not support multi-level deep introspection. (That would be a natural addition, but it wasn't needed at the time.) Here's the snippet:
javascript
function shapeCheck(x,shape) {
let good = true;
for (const name in shape) {
if (typeof x[name] === "undefined") {
good = false;
console.error(x,"missing",name);
continue;
}
if (shape[name].startsWith("?")) {
if (x[name] === null ||
typeof x[name] === shape[name].slice(1)) continue;
} else {
if (typeof x[name] === shape[name]) continue;
}
console.error(x,`has wrong type on ${name}: should be`,shape[name]);
good = false;
}
return good;
}
It's designed to exit late, so that as many errors are found as possible. Happy coding!
Previous Use our Code posts: 1. Better errors for shader compilation 2. WebGL Type Info 3. Matrix pretty printing 4. Math Library API Design