pravdomil pravdomil - 12 days ago 87
TypeScript Question

TypeScript check instance class via user defined type guard

Well, I have implemented

isInstanceOfClass
function, so that it can tell if the instance is instance of given class, now I need to write correct typing for it.

class Parent {
isInstanceOfClass<T>(arg: T): this is T {
// already implemented
}
}

class FooClass extends Parent {
foo: number;
}

class BarClass extends Parent {
bar: number;
}


Example:

let foo: Parent;
if(foo.isInstanceOfClass(FooClass)) {
foo.foo = 1; // TS2339: Property 'foo' does not exist on type 'Parent & typeof FooClass'.
}


Can somebody help me get rid of the error?

For various reasons I can only change the
isInstanceOfClass
method signature, not the example code.

Answer Source

You're almost there!
It should be:

class Parent {
    isInstanceOfClass<T>(arg: { new(): T }): this is T {
        // already implemented
    }
}

The difference is that what you're passing to isInstanceOfClass is not the instance but the class.
Once you change it to be the class (constructor) then the error goes away.