The maximum number of elements (inclusive). Must be a non-negative integer literal.
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)
Branded readonly array type for arrays with at most
MaxLengthelements.Unlike the structural tuple-based
MaxLengthTuple, the length constraint is encoded only in the brand, so the element typeElmnever gets multiplied into tuple positions or tuple unions. This keeps type-checking cost (instantiation count / memory) independent of the size ofElmand nearly independent ofMaxLength, and also supports large bounds (e.g.1000) that make the tuple-based family hit the recursion limit. Prefer this type whenElmis 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, thenMaxLengthArray<M, Elm>is assignable toMaxLengthArray<N, Elm>(an array of at mostMelements is also an array of at mostNelements). 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 inElm.