API reference › @evolu/common › Type › maxUtf8ByteLength
function maxUtf8ByteLength<Max extends number>(
max: ValidateBrandFactoryCount<Max>,
): BrandFactory<`MaxUtf8ByteLength${Max}`, string, MaxUtf8ByteLengthError<Max>>;
Defined in: packages/common/src/Type.ts:8396
String Brand limiting the UTF-8 encoding of a string to at most max
bytes.
maxLength counts UTF-16 code units, but storage, network protocols,
and file formats often limit the encoded size in bytes. UTF-8 encodes ASCII
in 1 byte, é in 2, € in 3, and an emoji such as 😀, which is two UTF-16
code units, in 4, so maxLength(n) alone allows up to 3 * n bytes.
The count equals the length of the bytes TextEncoder produces, without
encoding the string. TextEncoder replaces each lone surrogate with U+FFFD,
so a lone surrogate counts as 3 bytes; use wellFormed to reject lone
surrogates.
Example
import {
assertEqual,
assertErr,
assertOk,
assertType,
maxUtf8ByteLength,
String,
type Brand,
} from "@evolu/common";
const Label = maxUtf8ByteLength(8)(String);
assertType<typeof Label.Output, string & Brand<"MaxUtf8ByteLength8">>();
assertOk(Label.fromUnknown("café"), "café");
assertOk(Label.fromUnknown("😀😀"), "😀😀");
const invalid = Label.fromUnknown("€€€");
assertErr(invalid, { type: "MaxUtf8ByteLength8", value: "€€€", max: 8 });
assertEqual(
Label.formatError(invalid.error),
'The value "€€€" exceeds the maximum UTF-8 byte length of 8.',
);