I am not able to understand the code that I saw in a library which creates Tuple type.
type _TupleOf<T, N extends number, R extends unknown[]> = R['length'] extends N
? R
: _TupleOf<T, N, [T, ...R]>;
export type Tuple<T, N extends number> = N extends N
? number extends N
? T[]
: _TupleOf<T, N, []>
: never;
And it is used
Tuple<string, 10>
I am new to typescript. But this is what I understood.
In Tuple type
I can't understand what N extends N does here since it will always be true.
number extends N checks whether it's literal type or number type based on that, it will either return either an array or a tuple.
For example:
Tuple<string,number> //string[]
Tuple<string,2> // [string,string]
And In _TupleOf
R['length'] extends N checks the size is the same as N or not.
I can't understand what N extends N does in Tuple type.
The _TupleOf type takes in the union T for the items. It also takes in a draft array for the current accumulator of the draft tuple. Basically, it checks if the current length of the tuple accumulator is equal to the given number for the desired tuple size. If so, return the accumulator, otherwise recurse and add a new item to the draft tuple type with the T union provided. The length of the given R for the accumulator tuple will then increment by one to account for the next item. Therefore, the type as a whole just does a simple loop while pushing to a draft array while checking if the new array's length is equal to the target length. Here is an example in TypeScript code if it makes it easier to understand:
function tupleOf<T>(item: T, n: number, draft: T[] = []): T[] {
if (draft.length === n) { // the exit clause
return draft;
}
draft.push(item); // the pushing part
return tupleOf(item, n, draft);
}
const foo = tupleOf("Hey", 5);
console.log(foo); // ["Hey", "Hey", "Hey", "Hey", "Hey"]
TypeScript Playground Link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With