microsoft / microsoft/TypeScript

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

Open
#17,253 9 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Domain: check: Control Flow Possible Improvement
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the supplied TypeScript reproduction and trace how the instanceof guard narrows the value returned by the generic class factory. Verify the behavior using the shown assignments, then ensure the guarded string assignment is reported as a type error while the numeric assignment remains valid.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.