Last active
November 22, 2024 15:20
-
-
Save krystalcampioni/cd75ea3981a2d83e77527af600c2ee15 to your computer and use it in GitHub Desktop.
Typescript Enforce Array Max Length Type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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