type-challenges-solutions icon indicating copy to clipboard operation
type-challenges-solutions copied to clipboard

type-challenges-solutions/en/medium-last

Open utterances-bot opened this issue 4 years ago • 8 comments

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

utterances-bot avatar Apr 26 '21 21:04 utterances-bot

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

nonwip avatar Apr 26 '21 21:04 nonwip

@dvlden please ask follow-up questions and we will try to come up with a better explanation.

ghaiklor avatar Apr 28 '21 10:04 ghaiklor

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 avatar Jul 31 '21 16:07 jfet97

@jfet97 is this requirement reflected in tests? I don't remember having such test cases there 🤔

ghaiklor avatar Aug 01 '21 09:08 ghaiklor

@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 avatar Aug 01 '21 09:08 jfet97

@jfet97 I'm just a guy who solves the challenge until tests are passing, no blame on me 🤣

ghaiklor avatar Aug 01 '21 09:08 ghaiklor

I believe this question should be better labeled Last of tupple xd

dca123 avatar Sep 19 '22 14:09 dca123