2

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I always forgot the { new(): T } thing!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.