Hacker News new | ask | show | jobs
by theteapot 793 days ago
> Anytime I’ve come across the need to do this, I’ve found a class is a better and less complicated solution ... As far as I understand classes are the only real way to get nominal typing in TypeScript.

How are classes going to help? As far as I understand TS is structural period. Ex this is valid (!):

  class Email {
      constructor(public email: String) {}
  }
  let x: Email = new Email('foo@foo.com')
  let y = { email: '73'}
  x = y;
2 comments

I had the same initial reaction, but it turns out that if you have at least one private member, even with the same signature, it works as the parent comment suggests.

For example, these two classes are distinct to TypeScript:

    class Name {
        constructor(private value: string) {}

        getValue() {
            return this.value;
        }
    }

    class Email {
        constructor(private value: string) {}

        getValue() {
            return this.value;
        }
    }

    const email: Email = new Name(“Tim”); // Error: (paraphrasing) conflicting private declaration of “value”.
You’re right. This is what I meant, but I was not at all clear in my original comment.
I believe what the OP meant by "to get nominal typing in TypeScript" is that the type information is available at runtime through the use of the `instanceof` keyword.

I am surprised your code doesn't give an error, x and y are definitely not the same thing because `x instanceof Email` would be false at the end of that code. But like you said, to TS x and y are indeed the same type because they have the same structure. In practice both can be used interchangeably in the code (even if Email extended another class) with the sole exception of the `instanceof` keyword.