type-challenges-solutions/en/medium-last
Last of Array
This project is aimed at helping you better understand how the type system works, writing your own utilities, or just having fun with the challenges.
https://ghaiklor.github.io/type-challenges-solutions/en/medium-last.html
I still do not understand how this is done. The solution isn't clear to me at all... 🤷♂️ One point as improvement, I'd personally make is:
[...infer _, infer L]
// ^ as we don't really use X anywhere
@dvlden please ask follow-up questions and we will try to come up with a better explanation.
I suggest a little improvement. Despite the name of the challenge, this solution fails if an array type is used:
type test = Last<Array<number>> // inferred as never
But the last element will be a number!
My suggestion is:
type Last<T extends any[]> =
T extends [...any[], infer TAIL] ?
TAIL :
T extends (infer E)[] ?
E :
never
@jfet97 is this requirement reflected in tests? I don't remember having such test cases there 🤔
@jfet97 is this requirement reflected in tests? I don't remember having such test cases there 🤔
Nope. But it has seemed to me weird that the solution to the challenge "Last of Array" does not work for arrays 🤣.
@jfet97 I'm just a guy who solves the challenge until tests are passing, no blame on me 🤣
I believe this question should be better labeled Last of tupple xd