英文:
Extract type of last element of tuple in TypeScript
问题
You can achieve the desired type LastElementOf<T>
using conditional types in TypeScript. Here's the code to define such a type:
type LastElementOf<T extends any[]> = T extends [...infer Rest, infer Last] ? Last : never;
This type definition will correctly extract the type of the last element in the array or tuple T
.
英文:
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).
答案1
得分: 3
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
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论