0

I've just came across a TypeScript exercise, requiring the user to define custom LastElementOfArray type. The solution looks like this:

    type Last<A extends Array<any>> = A extends [...infer _, infer L] ? L : never

But something is weird. If the used syntax is 'spread', why is there an inconsistency with how JavaScript handles 'spread'? Specifically, the spread variable must be the last one - this JavaScript code returns a SyntaxError:

    const a = [1,2,3,4,5];
    (([...rest, e4, e5])=>{console.error(e4,e5)})(a)

Why does this 'inconsistency' exist? Is there any documentation on this? I've looked but found nothing.

Any help is appreacited.

fmi21
  • 485
  • 3
  • 15
  • Possible duplicate of [Destructuring to get the last element of an array in es6](https://stackoverflow.com/questions/33064377/destructuring-to-get-the-last-element-of-an-array-in-es6)? – eroironico Dec 06 '22 at 11:20
  • I am aware that this does not work in ES6. My question is rather, why does TypeScript implement the destructuring differently and whether there is any documentation on it. – fmi21 Dec 06 '22 at 11:25
  • 1
    Basically typescript knows that if an array has a type of `Array` then the last element would be `string | number` or if an array has a type of `[number, string, boolean]` then the last element would be `boolean`. Typescript doesn't know what you put inside the array, but it has the type of that array and can "guess" what type would be the last element – eroironico Dec 06 '22 at 11:35
  • This makes sense. It would still be nice to see some docs - I think a difference like that should be documented? – fmi21 Dec 06 '22 at 11:39
  • Yep, i also don't like typescript's docs, but luckly there's stackoverflow :DD – eroironico Dec 06 '22 at 11:45
  • 1
    This is covered in some level of descriptiveness in the [Variadic Tuple Types](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-0.html#variadic-tuple-types) section of the TS 4.0 release notes. However, I'm not sure whether or not "What's the URL to a documentation page for X?" is [on-topic](https://stackoverflow.com/help/on-topic) for SO. – jsejcksn Dec 06 '22 at 12:09

0 Answers0