API reference@evolu/commonType › IntFromString

const IntFromString: transform(
  "IntFromString",
  String,
  Int,
  {
    from: (value): Result<number, IntFromStringError> =>
      /^-?\d+$/u.test(value)
        ? ok(globalThis.Number(value))
        : err({ type: "IntFromString", value }),
    to: (value) =>
      globalThis.Object.is(value, -0) ? "-0" : globalThis.String(value),
  },
  (error) =>
    `The value ${safelyStringifyUnknownValue(error.value)} is not a decimal integer.`,
);

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

Transforms a decimal integer string into an Int.

This is useful for inputs that carry numbers as text, such as environment variables, URL query parameters, and form fields. The string must consist of an optional minus sign and digits; the Int constraint then rejects values outside the safe integer range.

Example

import {
  assertEqual,
  assertErr,
  assertOk,
  assertSame,
  IntFromString,
} from "@evolu/common";

assertOk(IntFromString.fromUnknown("4000"), 4000);
assertOk(IntFromString.fromUnknown("-1"), -1);
assertEqual(IntFromString.to(IntFromString.orThrow("42")), "42");

const negativeZero = IntFromString.orThrow("-0");
assertSame(negativeZero, -0);
assertEqual(IntFromString.to(negativeZero), "-0");

const invalid = IntFromString.fromUnknown("4000.5");
assertErr(invalid, { type: "IntFromString", value: "4000.5" });
assertEqual(
  IntFromString.formatError(invalid.error),
  'The value "4000.5" is not a decimal integer.',
);