iTranslated by AI
Techniques behind ts-array-length
Hello everyone. I recently released a library for TypeScript called ts-array-length.
In this article, I will introduce this library and explain how its implementation works.
Features of ts-array-length
ts-array-length provides three functions, and by using them, you can actually check the number of elements in an array.
For example, by using hasLength, you can check if an array has exactly 2 elements.
if (hasLength(arr, 2)) {
// arr is an array with 2 elements!
const [first, last] = arr;
}
Additionally, there are hasMinLength to determine if the number of elements is above a certain value, and isNonEmpty to determine if there is at least one element.
if (hasMinLength(arr, 3)) {
// arr has 3 or more elements
}
if (isNonEmpty(arr)) {
// arr has 1 or more elements
}
This is incredibly revolutionary. The day ts-array-length reaches Mars is not far off.
Why is ts-array-length necessary?
...Just kidding, but why are such functions necessary? Of course, it's for type checking.
Specifically, these functions are useful when TypeScript's noUncheckedIndexedAccess option is enabled. Under this option, index access to an array is always treated as potentially undefined.
// arr: string[]
const first = arr[0];
// ^? const first: string | undefined
And currently, TypeScript does not take the result into account even if you check arr.length using an if statement or similar.
if (arr.length > 0) {
// It still results in string | undefined...
const first = arr[0];
}
So, I created ts-array-length so that the type is narrowed down upon checking. For example, in the case of hasLength, the following narrowing is provided:
// Here, arr is of string[] type
if (hasLength(arr, 2)) {
// Here, arr is of readonly [string, string] type
}
In TypeScript, to perform user-defined narrowing, you need to go through a function call, so it is provided in the form of a function like this.
While there is a possibility of things breaking if you make destructive changes to arr inside the narrowed if statement, this is a common issue with most type narrowing, so I'll turn a blind eye this time. 🙈
When is ts-array-length useful?
As mentioned above, ts-array-length is useful when TypeScript's noUncheckedIndexedAccess option is enabled. This is a strict option that is not turned on by default even if strict is set to true, but you should definitely enable it because otherwise, undefined that does not appear in the types can emerge.
While it might seem inconvenient to always have the possibility of undefined, you should first try to avoid using index access as much as possible. Instead, using methods like for-of loops, forEach, or map will prevent undefined from appearing. However, there are still situations where index access is necessary.
Furthermore, when enabling noUncheckedIndexedAccess in a codebase where it was not previously active, there may be many parts of the code dependent on index access. In such cases, ts-array-length is effective for resolving type errors with minimal changes.
Behind the scenes of ts-array-length
From here, I will explain how ts-array-length is implemented. As noted before, a function is required for type narrowing. By setting the return value of a function to the form parameterName is Type (a type predicate), it signifies that if the function returns true, the parameterName is narrowed to that Type.
Specifically, hasLength, hasMinLength, and isNonEmpty are implemented as follows:
export function hasLength<T, N extends number>(
arr: readonly T[],
length: N,
): arr is ReadonlyArrayExactLength<T, N> {
return arr.length === length;
}
export function hasMinLength<T, N extends number>(
arr: readonly T[],
length: N,
): arr is ReadonlyArrayMinLength<T, N> {
return arr.length >= length;
}
export function isNonEmpty<T, N extends number>(
arr: readonly T[],
): arr is ReadonlyArrayMinLength<T, 1> {
return arr.length >= 1;
}
The core of this library consists of ReadonlyArrayExactLength and ReadonlyArrayMinLength, which are used as the target types for narrowing. ReadonlyArrayExactLength<T, N> is an array of type T with exactly N elements. ReadonlyArrayMinLength<T, N> is an array of type T with N or more elements. These types can be implemented using TypeScript's tuple types.
Creating a tuple type with a specified number of elements
The basic idea for implementing such a type is explained in the following article, but I will briefly explain it again here.
For example, a tuple type with exactly 2 elements can be expressed as the [T, T] type, and a tuple type with 2 or more elements can be expressed as [T, T, ...T[]].
Therefore, we consider implementing a type that generates the above types when the number of elements is given as a numeric literal type, such as ReadonlyArrayExactLength<T, 2>.
The implementation can be achieved by recursing the type in TypeScript, taking advantage of the fact that "a new tuple type can be created by adding one element to an existing tuple type" and "the number of elements in a tuple type can be obtained as a literal type by looking at the length property." The basic implementation is as follows:
export type ReadonlyArrayExactLength<T, N extends number> =
ReadonlyArrayExactLengthRec<T, N, readonly []>;
type ReadonlyArrayExactLengthRec<
T,
L extends number,
Result extends readonly T[],
> = Result["length"] extends L
? Result
: ReadonlyArrayExactLengthRec<T, L, readonly [T, ...Result]>;
ReadonlyArrayExactLengthRec determines whether the tuple type given to Result has L elements. If not, it adds one element to Result and recurses. When the number of elements in Result reaches L, it terminates the recursion and returns Result.
The calculation is performed roughly as follows:
ReadonlyArrayExactLength<T, 2>
= ReadonlyArrayExactLengthRec<T, 2, readonly []>
= ReadonlyArrayExactLengthRec<T, 2, readonly [T]>
= ReadonlyArrayExactLengthRec<T, 2, readonly [T, T]>
= readonly [T, T]
I will omit the details, but ReadonlyArrayMinLength has a similar implementation.
Refining the implementation to handle various use cases
While the above is the basic idea, the actual implementation in ts-array-length is slightly more complex. This is to ensure it works correctly even when used in unexpected ways.
Handling union types
First, let's consider a case where N is a union type.
ReadonlyArrayExactLength<string, 1 | 2 | 3>
In this case, since it means "1, 2, or 3 elements," we would expect the result to be [string] | [string, string] | [string, string, string]. However, with the implementation above, it doesn't work that way; it actually becomes [string]. The reason is that in the part where it checks if the length of Result has reached N, since N is 1 | 2 | 3, it interprets the condition as "terminate recursion if the length is 1, 2, or 3."
ReadonlyArrayExactLength<T, 1 | 2 | 3>
= ReadonlyArrayExactLengthRec<T, 1 | 2 | 3, readonly []>
= ReadonlyArrayExactLengthRec<T, 1 | 2 | 3, readonly [T]>
= readonly [T]
To improve this behavior, union distribution is effective. This is a mechanism in TypeScript that allows you to calculate results for each constituent element of a union type separately and then combine those results back into a union type. Specifically, the implementation is modified as follows (the implementation of ReadonlyArrayExactLengthRec remains the same and is omitted here):
export type ReadonlyArrayExactLength<T, N extends number> =
N extends number
? ReadonlyArrayExactLengthRec<T, N, readonly []>
: never;
The implementation now includes a conditional branch (conditional type) using N extends number. Since the type parameter constraint already specifies N extends number, this branch is technically always true and might seem redundant.
However, in TypeScript, when the condition part of a conditional type takes the form "TypeParameter extends Type", union distribution occurs. If the TypeParameter is a union type, the calculation is performed separately for each constituent element of the union, and the results are then combined. In this case, if N is 1 | 2 | 3, the type calculation will be split into cases where N is 1, 2, and 3 respectively.
In other words, with the new implementation, ReadonlyArrayExactLength<T, 1 | 2 | 3> is calculated as follows:
ReadonlyArrayExactLength<T, 1 | 2 | 3>
= ReadonlyArrayExactLengthRec<T, 1, readonly []> | ReadonlyArrayExactLengthRec<T, 2, readonly []> | ReadonlyArrayExactLengthRec<T, 3, readonly []>
Now we have achieved the intended behavior. By utilizing union distribution, TypeScript can handle union types quite flexibly, which is extremely useful when implementing complex types like those discussed in this article.
Handling when number is passed to N
The types implemented this time make sense when a specific number is provided for N. Therefore, a specification like ReadonlyArrayExactLength<T, number> doesn't have much meaning. However, to make it a highly versatile type, we must handle such cases as well.
The type ReadonlyArrayExactLength<T, number> means that any length that is a number is fine, so it seems reasonable to interpret it as having no restrictions. In other words, in this case, returning readonly T[] would be appropriate. Since we need to include a branch for this case, we can do the following:
export type ReadonlyArrayExactLength<T, N extends number> =
number extends N
? readonly T[]
: N extends number
? ReadonlyArrayExactLengthRec<T, N, readonly []>
: never;
What was added is the initial branch number extends N. This means "number is a subtype of N," so N must be a type that can accept all number values. In this case, since the constraint N extends number is also applied, this serves as the condition that N is the number type itself.
Handling when N is not a non-negative integer
Up until now, we have assumed that N will be a non-negative integer, but in reality, values like -3 or 0.5 could be given to N. We need to address these cases.
With the current implementation, an error like the following occurs. This means the type calculation did not finish even after reaching the recursion limit. In this case, the error appears because the type calculation enters an infinite loop.
// Error: Type instantiation is excessively deep and possibly infinite.(2589)
type A = ReadonlyArrayExactLength<string, -3>
In the calculation of ReadonlyArrayExactLengthRec, the length of Result starts at 0 and proceeds to 1, 2, 3, and so on, continuing to increase the number of elements in Result until it matches N. If N is -3 or 0.5, the length of Result will never match, resulting in an infinite loop.
Since an array's length can never be -3 or 0.5, we need to prevent ReadonlyArrayExactLengthRec from calculating when a numeric type other than a non-negative integer is given as N. While we could use never to signify that such a value doesn't exist, to be safe, let's return readonly T[] without applying extra restrictions.
To achieve this, we need to determine whether the numeric literal type N is a non-negative integer. Let's try implementing this as IsCertainlyInteger<N>. However, since TypeScript does not support numeric calculations at the type level, this is not straightforward and a perfect determination is impossible. Nevertheless, a certain level of determination is possible using template literal types. Here is the implementation:
export type IsCertainlyInteger<N extends number> =
IsCertainlyIntegerImpl<`${N}`>;
type IsCertainlyIntegerImpl<Str extends string> =
Str extends `${infer _}.${infer _}`
? false
: Str extends `-${infer _}`
? false
: Str extends "Infinity" | "-Infinity" | "NaN"
? false
: true;
In this implementation, IsCertainlyInteger converts the given N into a string literal type `${N}` and passes it to IsCertainlyIntegerImpl. The strategy is to perform the determination as a string, since TypeScript can handle type-level calculations on strings. For example, if N is the literal type 3, it becomes the type "3" after conversion to a string type. Similarly, -3 becomes "-3", and 0.5 becomes "0.5".
Looking at the implementation above with that in mind, it "rejects strings that contain a . after conversion, strings that start with -, and Infinity or NaN." This effectively filters out negative numbers and decimals. However, it might mistakenly reject large values like 1.23e+100. In this case, it's not a problem since there are no use cases for such large numeric values.
Integrating the above type function, ReadonlyArrayExactLength looks like the following. Now, even if a negative number or decimal is given as N, it will not enter an infinite loop.
export type ReadonlyArrayExactLength<T, N extends number> =
number extends N
? readonly T[]
: N extends number
? IsCertainlyInteger<N> extends true
? ReadonlyArrayExactLengthRec<T, N, readonly []>
: readonly T[]
: never;
When providing useful type functions as a library, it is good practice to make them resilient to as many various inputs as possible.
Drawbacks of the implementation
While the actual implementation of ts-array-length incorporates all the techniques mentioned above, it does have some drawbacks. For example, providing a large integer for N, such as ReadonlyArrayExactLength<string, 1000>, will hit the recursion limit and result in an error. While the limit could be increased by improving the efficiency of tuple type generation, support for such large numbers didn't seem very necessary, so it was omitted this time.
Conclusion
In this article, I introduced ts-array-length, which I created for a specific reason, and explained its implementation in detail. While it is difficult to provide a systematic explanation for this kind of type-level implementation, I hope this concrete example serves as a useful reference for you.
Discussion