Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Session 7: Private Class Members And Nominal Typing #41

Open
JamieB-gu opened this issue Dec 13, 2023 · 1 comment
Open

Session 7: Private Class Members And Nominal Typing #41

JamieB-gu opened this issue Dec 13, 2023 · 1 comment

Comments

@JamieB-gu
Copy link
Contributor

We should probably mention in the session that the moment you create a private member in a class, you effectively achieve Nominal typing in TypeScript!

Suggested here:

#40 (review)

@mxdvl
Copy link
Contributor

mxdvl commented Dec 13, 2023

class Named {
    #name: string;
    constructor(name: string) {
        this.#name = name;
    }

    get name() { return this.#name }
}

class Person {
    #name: string; // this is sufficient to create incompatible classes
    job: string;
    constructor(name: string, job: string) {
        this.#name = name;
        this.job = job;
    }

    get name() { return this.#name }
}

const cpScott = new Person('CP Scott', 'Journalist',);

const hello = (named: Named): string =>
    `Hello ${named.name}`;

const helloCPScott = hello(cpScott);
// Argument of type 'Person' is not assignable to parameter of type 'Named'.
//  Property '#name' in type 'Person' refers to a different member that cannot be accessed from within type 'Named'.(2345)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: Todo
Development

No branches or pull requests

2 participants