Comment

Comment by andrew_n

Programming TypeScript has a section on “Simulating Nominal Types” [1]. You define a type that’s impossible to create naturally, and provide a function that asserts something is of that type.

    type CompanyID = string & {readonly brand: unique symbol}
    type OrderID = string & {readonly brand: unique symbol}
    type UserID = string & {readonly brand: unique symbol}
    type ID = CompanyID | OrderID | UserID

    function CompanyID(id: string) {
      return id as CompanyID
    }
    ...
TypeScript can be very confusing sometimes, and given the learning curve I’d caution someone trying to learn modern JS away from starting out with it. But in even small codebases it’s an amazing improvement in safety, especially for refactoring.

[1] https://learning.oreilly.com/library/view/programming-typesc...

parent andrew_n 6 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton