microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
100.75k stars 12.46k forks source link

Assertion Functions cannot assert over private properties - unnecessary/wrong error message? #47778

Open phryneas opened 2 years ago

phryneas commented 2 years ago

Assertion Function "Private identifiers are not allowed outside class bodies."

Bug Report

🔎 Search Terms

assertion function, asserts, #, private members, Private identifiers are not allowed outside class bodies.

🕗 Version & Regression Information

This happens in 4.0.5, 4.4.3, 4.5.4 and the latest nightlies - so probably in all TS versions that support assertion functions and private class members.

⏯ Playground Link

A playground showcasing the problem

💻 Code

class Test {
    #ready: boolean = false;

    #assertReady(): asserts this is {
        // Private identifiers are not allowed outside class bodies.(18016)
        #ready: true // this is working perfectly fine though...
    } {
        if (this.#ready) {
            throw new Error("not ready")
        }
    }
}

🙁 Actual behavior

The code above works 100% as expected (the assertion function also narrows the type of this.#ready down to true correctly), but TS displays an error message:

Private identifiers are not allowed outside class bodies.(18016)

🙂 Expected behavior

The error message should be removed - this seems to work absolutely fine as it is. The error message seems to be a red herring.

nmain commented 2 years ago

The quick info on that function is a bit wonky:

(method) Test.#assertReady(): asserts this is {
    "__#46@#ready": true;
}

Where the number 46 goes up as you edit the document.

RyanCavanaugh commented 2 years ago

The error is intentional. While it may appear to work, this hasn't been designed or tested at all, so there might be dragons lurking, hard to say.

MartinJohns commented 2 years ago

@nmain #36548