Skip to content

__TS__InstanceOf errors when left-hand value compiles to userdata, function, boolean or number #835

@chrisbajorin

Description

@chrisbajorin

All of the following if-statements will have the same error with their respective types.

class SomeClass {
}

const co: any = coroutine.create(() => {});
if (co instanceof SomeClass) {}

const fn: any = () => {};
if (fn instanceof SomeClass) {}

const bool: any = true;
if (bool instanceof SomeClass) {}

const num: any = 5;
if (num instanceof SomeClass) {}
/usr/local/opt/lua/bin/lua5.3: dist/bundle.lua:716: attempt to index a thread value (local 'obj')
stack traceback:
	dist/bundle.lua:716: in function '__TS__InstanceOf'

Some are a bit contrived, and casting as any was need to get TS to compile for some of them. However, a more real-life case happens when you have a type union:

class SomeClass {
    constructor(public someFn: (this: void) => void) {}
}

function takesClassOrFunction(clsOrFn: SomeClass | ((this:void) => void)): void {

    if (clsOrFn instanceof SomeClass) {
        return clsOrFn.someFn()
    } else {
        return clsOrFn();
    }
}

const noop = () => {};
const cls = new SomeClass(noop);
takesClassOrFunction(cls);
takesClassOrFunction(noop);

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions