Dev Helpers
← Back

Create a positive ID at a validation boundary

Create a positive ID at a validation boundary using TypeScript.

Open this example in the interactive library

Source code

type Brand<T, Name extends string> = T & { readonly __brand: Name };
console.log(
  ((n: number): Brand<number, "JobId"> => {
    if (!Number.isInteger(n) || n <= 0) throw Error("Invalid ID");
    return n as Brand<number, "JobId">;
  })(7),
);

Sample output

7