typesafe-ts API Documentation - v1.5.1
    Preparing search index...

    Function apply_brand

    • Modifies a value by applying a runtime brand. Brands can be used to create nominal types in TypeScript so that structurally equivalent values are not assignable. At runtime the brand can be used to discriminate union types and works reliably even in cases where instanceof does not.

      The brand is stored using a unique symbol (brand.symbol), which guarantees it will not conflict with any properties from other tools, libraries, or your own code.

      Type Parameters

      • T extends BrandableTypes
      • const BrandString extends string

      Parameters

      • value: T extends Brand<UnderlyingType, ExistingBrand>
            ? TypeAlreadyBrandedError<UnderlyingType, ExistingBrand>
            : T

        The value to apply a brand to.

      • brand_string: BrandString

        A string literal used to create a unique brand type and runtime brand.

      Returns Brand<T, BrandString>

      The input value with its type modified to include the brand, and a non-enumerable property added to the runtime value.

      import { brand, type Brand } from "typesafe-ts/brand";

      type UserId = Brand<{ id: string }, "UserId">;
      type ProductId = Brand<{ id: string }, "ProductId">;

      const userId: UserId = brand.apply({ id: "user-123" }, "UserId");
      const productId: ProductId = brand.apply({ id: "prod-456" }, "ProductId");

      function getUser(id: UserId) { ... }

      getUser(userId); // OK
      getUser(productId); // Type error: ProductId is not assignable to UserId