API reference › @evolu/common › Type › ValidateBrandFactoryNumber

type ValidateBrandFactoryNumber<Value extends number> =
  IsUnion<Value> extends false
    ? {} extends Record<`${Value}`, never>
      ? Value & Readonly<Record<BrandFactoryNumberError, never>>
      : Value
    : Value & Readonly<Record<BrandFactoryNumberError, never>>;

Defined in: packages/common/src/Type.ts:6504

Numeric parameter preserving literal types in a BrandFactory.

Numeric parameters encoded in a Brand name must preserve their literal types. Inline literals and const values do. Arithmetic expressions and runtime numbers widen to number, while branded numbers can contain many runtime values. Both are rejected so distinct constraints do not all share one broad Brand.

Example

import {
  assertType,
  Number,
  brand,
  err,
  ok,
  type Brand,
  type BrandFactory,
  type TypeError,
  type ValidateBrandFactoryNumber,
} from "@evolu/common";

interface LessThanError<
  Max extends number,
> extends TypeError<`LessThan${Max}`> {
  readonly value: number;
  readonly max: Max;
}

const lessThan =
  <Max extends number>(
    max: ValidateBrandFactoryNumber<Max>,
  ): BrandFactory<`LessThan${Max}`, number, LessThanError<Max>> =>
  (parent) => {
    const name = `LessThan${max}` as `LessThan${Max}`;

    return brand(
      name,
      parent,
      (value) =>
        value < max
          ? ok()
          : err<LessThanError<Max>>({ type: name, value, max }),
      () => `Expected a number less than ${max}.`,
    );
  };

const LessThan100 = lessThan(100)(Number);
type LessThan100 = typeof LessThan100.Output;

assertType<typeof LessThan100.name, "LessThan100">();
assertType<LessThan100, number & Brand<"LessThan100">>();

// @ts-expect-error Arithmetic expressions widen to number.
lessThan(100 - 1)(Number);