kungfooman / RuntimeTypeInspector.js

Checking JSDoc types at runtime for high-quality types - Trust is good, control is better.
MIT License
8 stars 0 forks source link

Validate import namespace specified functions properly #143

Closed kungfooman closed 7 months ago

kungfooman commented 7 months ago

image

This error is caused by:

https://github.com/kungfooman/RuntimeTypeInspector.js/blob/3ec2e102ff613d259fa9b7dcc18653eee5109879/src-runtime/inspectType.js#L21-L34

Clearly the instance of a class isn't a function - otherwise the logic works for other primitive types like numbers.

So I need some special casing for the case of importNamespaceSpecifiers[a][b].constructor

We may be tempted to use importNamespaceSpecifiers[a][b].name, but I don't think this goes far enough - after all you can make nameless classes/functions:

function a() {
    return () => {}
}
f = a()

image

Or in more familiar terms:

function makeVec3Class() {
    return function() {
        this.x = 1;
        this.y = 2;
        this.z = 3;
    }
}
const Vec3 = makeVec3Class();
vec = new Vec3

Output:

image

It seems that TypeScript is itself confused:

/**
 * @param {B.Vec3} vec - The vector.
 */
function testVec(vec) {
  console.log("testVec got", {vec});
}
testVec(new B.Vec3());

image

Error:

Argument of type '(Anonymous function)' is not assignable to parameter of type 'typeof (Anonymous function)'.
  Type '(Anonymous function)' provides no match for the signature '(): void'.ts(2345)
(alias) new Vec3(): (Anonymous function)
export Vec3

Right now I'm tempted to imply that any import namespace specifier function assumes an object with given function as prototype:

if (value.constructor === importNamespaceSpecifiers[a][b]) {
  return true;
}