Hacker News new | ask | show | jobs
by eyelidlessness 1470 days ago
A common approach in TypeScript, which doesn’t require a wrapping object or any runtime overhead, is called “branding” (or a variety of other names for similar concepts). It works by applying additional metadata about the value which makes it nominally incompatible with other values of the same underlying type. You can accomplish this a variety of ways, all of which have some tradeoffs. My (current) preference is to declare a class where the metadata is defined as a generic value assigned to a private property or a unique symbol, e.g.:

  declare class Branded<Meta> {
    private meta: Meta;
  }

  type Brand<T, Meta> = T & Branded<Meta>;

  type UInt = Brand<number, 'UInt’>;