Skip to content

Properties of instances of anonymous classes have type <any> after an instanceof guard. #17253

Open
@pbazant

Description

@pbazant

TypeScript Version: 2.4.1

Code

function create_my_class<T>() {
    return class {
        value: T;
        constructor(
            value: T
        ) {
            this.value = value;
        }
    }
}
const MyClassWithNumber = create_my_class<number>();
const with_number = new MyClassWithNumber(234);

with_number.value = 10;
// with_number.value = "sdf"; // error, and rightly so

const something: any = with_number;

if(something instanceof MyClassWithNumber) {
    something.value = 20;
    something.value = "sdf"; // not an error, but should be one
}

Expected behavior:
The last assignment should be marked as a type error by TS.

Actual behavior:
The last assignment is not marked as error. This is somewhat surprising, as the line

with_number.value = "sdf";

is righteously reported as a type error by TS.

Not a huge issue, but prevented me from using a class factory.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions