API reference@evolu/commonBytes › ByteSizeLiteral

ByteSizeLiteral:  createTypeWithError(
  "ByteSizeLiteral",
  byteSizeLiteralSyntax,
  (cause, value): ByteSizeLiteralError => ({
    type: "ByteSizeLiteral",
    value,
    cause,
  }),
  (error) =>
    The value ${safelyStringifyUnknownValue(error.value)} is not a byte-size literal. Use a value such as "512KiB" or "1MiB".,
) ;

Defined in: packages/common/src/Bytes.ts:1785

Byte length literal Type with compile-time and runtime validation.

Supported formats:

  • Bytes: 0B to 1023B
  • KiB: 1KiB to 1023KiB or 1.5KiB to 1023.5KiB
  • MiB: 1MiB to 1023MiB or 1.5MiB to 1023.5MiB
  • GiB: 1GiB to 1023GiB or 1.5GiB to 1023.5GiB
  • TiB: 1TiB to 1023TiB or 1.5TiB to 1023.5TiB

Units are the binary ones defined by IEC, named kibibyte (KiB, 1024 bytes), mebibyte (MiB), gibibyte (GiB), and tebibyte (TiB), each 1024 times the previous. Memory, storage quotas, and caches are measured in them. The familiar MB is ambiguous: SI defines it as a million bytes, storage vendors use that meaning, and most software uses 1048576 instead, which is why a "1 TB" drive shows as 931 "GB". MiB has only one meaning, so a literal never depends on a convention.

Each unit is bounded below 1024, so equivalent representations are avoided: 1024KiB must be written as "1MiB". A half is the only decimal allowed, because it is the only single decimal digit that is exact in every binary unit; 1.1KiB would be 1126.4 bytes. For other exact values, use ByteLength directly.

See ByteSize for a type that also accepts ByteLength. Use byteSizeToByteLength to convert.

Invalid values produce a ByteSizeLiteralError.

Example

import {
  assertEqual,
  assertErr,
  assertFalse,
  assertOk,
  assertType,
  ByteSizeLiteral,
} from "@evolu/common";

// The TypeScript type accepts valid spellings and rejects the rest.
const literal: ByteSizeLiteral = "1023MiB";
assertType<Extract<ByteSizeLiteral, "1024KiB" | "1.1KiB" | "1MB">, never>();

// The runtime Type validates the same grammar.
assertOk(ByteSizeLiteral.fromUnknown(literal), "1023MiB");
assertFalse(ByteSizeLiteral.is("1024KiB"));

const invalid = ByteSizeLiteral.fromUnknown("1MB");
assertErr(invalid);
assertEqual(invalid.error.type, "ByteSizeLiteral");
assertEqual(
  ByteSizeLiteral.formatError(invalid.error),
  'The value "1MB" is not a byte-size literal. Use a value such as "512KiB" or "1MiB".',
);