Skip to content

Classes with private #fields are not treated as distinct when returned from functions #62664

@p2js

Description

@p2js

🔎 Search Terms

"class from functions", "classes returned from functions", "class type" functions, "ES2020", "private fields", "#private"

🕗 Version & Regression Information

I believe this behavior has not changed since the introduction of private #fields in classes. I reviewed the FAQ about anything relating to classes with #fields.

⏯ Playground Link

https://www.typescriptlang.org/play/?ssl=17&ssc=42&pln=1&pc=1#code/MYGwhgzhAECC0G9oGIwC5oQC4CcCWAdgOYDc0wA9gdjgK7BYU4AU6muhRAlItFgBZ4IAOlTQAvNDDQAvrIBQoSDABCvVBhqcylarnqMWbLcR5IBQ0dMnS5M+fJABTLFIzxJBJwHc4zAEQAEk4gIBT+XCSOLtAARhhqnj5+QSFhEWQA9JnQAKI4OEwYACoAngAOTtAA5LDV0ELQBBSuynhEBGCxznwUfBVV1SrVwtAACoWVOFilNaj1hP2VNXXQOE4AZk44MIxS0AAmeBtb6wSuALZOF7HbfPxgrsBgBM2ut1LAwE5QTgfQG0KF2g3jwFgIS0Gw2E8myeQKTAau34VQOPzw63+tweADc8BRaDhoCj1g55BtaAQGPiIVgflhmGZ5NAWWsXISIUooNAAHJgK7-JAadj4Yg6Kg0AxMViaDimXgWERiGxkOzyezRVwAYQkfHpjKizlcABFdXTsAaHEbyLqvL4tQEAIwZTWHDAzSoUDY2pK+Y1OjLQOE8vrbQo4IA

💻 Code

class A { #a: string; constructor(a: string) { this.#a = a } }
class B { #a: string; constructor(a: string) { this.#a = a } }

let a: A = new A("Hello");
let b: B = new A("Hello"); // Error: Type 'A' is not assignable to type 'B'. Property '#a' in type 'A' refers to a different member that cannot be accessed from within type 'B'.
// Error is the desired behaviour here


function test() {
    return class Named { #a: string; constructor(a: string) { this.#a = a; } }
}

let C = test();
let D = test();

let c = new C("1");
let d: typeof c = new D("1"); // No error

🙁 Actual behavior

a value of type D can be assigned to a value of type C without error.

🙂 Expected behavior

C and D are treated as distinct types like A and B, so the same error happens, ie. that the property #a of type D refers to a different member that cannot be accessed from within type C (typeof c).

Additional information about the issue

This would enable the ability to create new distinct class types dynamically which would be great for when you want to make unique types that cannot be satisfied by any other value.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions