Essentially, what I am trying to write is a function that accepts an array of different types, (do something with that), and then return a type based on only the last element in that array (previous elements have been processed, but only the last element is used for the return value).
I know I can write a function that returns an array based off of all element types as follows.
function arraymod<T extends unknown[]>(
...input: {
[index in keyof T]: ParamType<T[index]>
}
): T {
return input.map(unparam);
}
What I want is a function that does something like this.
function takelast<T extends unknown[]>(
...input: {
[index in keyof T]: ParamType<T[index]>
}
): LastElementOf<T> /* What would this return type be? */ {
return unparam(input[input.length - 1]);
(ParamType<T> and unparam are just some example types/functions for illustration)
How can I write a type LastElementOf<T> that gives the type of the last element of a tuple T (or array, eventhough that would just be type of any element).
>Solution :
We must use infer keyword to achieve this result.
We are going to check the array to extend infer last item and the rest of them, which we don’t care about:
type LastElementOf<T extends readonly unknown[]> = T extends readonly [...unknown[], infer Last]
? Last
: never;
...unknown[] will be first items except the last one, and the last one will be the infer Last
Usage:
type Case1 = LastElementOf<[]>; // never
type Case2 = LastElementOf<['dasd']>; // "dasd'
type Case3 = LastElementOf<['string', 12, false]>; // false
type Case4 = LastElementOf<readonly ['string', 12, false]>; // false