ts-type-forge
    Preparing search index...
    MaxLengthArray: readonly Elm[] & TSTypeForgeInternals_BrandEncapsulated<
        Readonly<{ MaxLength: UintRangeInclusive<0, MaxLength> }>,
    >

    Branded readonly array type for arrays with at most MaxLength elements.

    Unlike the structural tuple-based MaxLengthTuple, the length constraint is encoded only in the brand, so the element type Elm never gets multiplied into tuple positions or tuple unions. This keeps type-checking cost (instantiation count / memory) independent of the size of Elm and nearly independent of MaxLength, and also supports large bounds (e.g. 1000) that make the tuple-based family hit the recursion limit. Prefer this type when Elm is a large type or the bound is large.

    The brand is encoded so that the natural subtyping relation between length constraints is preserved: if M <= N, then MaxLengthArray<M, Elm> is assignable to MaxLengthArray<N, Elm> (an array of at most M elements is also an array of at most N elements). This is achieved by branding with the union of allowed lengths (0 | 1 | ... | MaxLength), which shrinks as the constraint gets stricter. The result is also covariant in Elm.

    Type Parameters

    • MaxLength extends SupportedLength

      The maximum number of elements (inclusive). Must be a non-negative integer literal.

    • Elm = unknown

      The type of elements in the array (defaults to unknown).

    const isMaxLengthArray = <N extends SupportedLength, E>(
    xs: readonly E[],
    maxLength: N,
    ): xs is MaxLengthArray<N, E> => xs.length <= maxLength;

    const tags = ['a', 'b', 'c'] as unknown as MaxLengthArray<8, string>;

    const relaxed: MaxLengthArray<16, string> = tags; // OK (8 <= 16)
    const widened: readonly string[] = tags; // OK
    // const strict: MaxLengthArray<2, string> = tags; // Error! (8 > 2)