Skip to content

Instantly share code, notes, and snippets.

@krystalcampioni
Last active November 22, 2024 15:20
Show Gist options
  • Save krystalcampioni/cd75ea3981a2d83e77527af600c2ee15 to your computer and use it in GitHub Desktop.
Save krystalcampioni/cd75ea3981a2d83e77527af600c2ee15 to your computer and use it in GitHub Desktop.
Typescript Enforce Array Max Length Type
/**
* Enforces that an array respects a maximum length.
*
* @param {T[] | undefined} array - The array to validate.
* @param {number} maxLength - The maximum length.
* @returns {(T[] & {length: number}) | undefined} - Returns the array if valid, otherwise undefined.
*/
export function enforceMaxLength<T, N extends number>(
array: T[] | undefined,
maxLength: N,
): (T[] & {length: N}) | undefined {
if (!array) {
return undefined;
}
if (array.length <= maxLength) {
return array as T[] & {length: N};
}
console.error(`Array exceeds maximum length of ${maxLength}`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment