Skip to content

Legitimate type assertion causes compiler error #7598

Closed
@philthy256

Description

@philthy256

Typscript version
Nuget package manager in Visual Studio reports it as v2.0.0
"tsc --v" reports it as v1.0.0.0

Code

class Animal {

    public speak() {
        if (this instanceof Dog) {
            var dog: Dog = <Dog>this;
            dog.woof();
        }
    }
}

class Dog extends Animal {
    public woof() {}
}

Expected behavior:

Should compile without issue. I expect to be able to assert that "this" is of type Dog, because it can be. I also note that "woof" is referred to as a property in the error message, when perhaps it should be referred to as a method.

Obviously in this case, it would make sense to override Animal.speak() in Dog rather than check the type in Animal.speak(), but sometimes it makes sense to check the type of "this" explicitly, perhaps because you want to perform some action in the middle of a method in the base class, between various other actions, and overriding doesn't make that possible.

In any case, good practice or bad practice, it's valid code and should compile.

Actual behavior:

Error TS2352 Neither type 'this' nor type 'Dog' is assignable to the other.
Type 'Animal' is not assignable to type 'Dog'.
Property 'woof' is missing in type 'Animal'.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions