type-fest icon indicating copy to clipboard operation
type-fest copied to clipboard

ArrayExceptLastElement type

Open Superpat opened this issue 3 months ago • 6 comments

Maybe there's a simpler way to do this, but here's a function that will get the inverse of LastArrayElement:

export type ArrayExceptLastElement<Elements extends readonly unknown[], ElementBeforeTailingSpreadElement = never> =
	// If the last element of an array is a spread element, the `LastArrayElement` result should be `'the type of the element before the spread element' | 'the type of the spread element'`.
	Elements extends readonly []
		? ElementBeforeTailingSpreadElement
		: Elements extends readonly [...infer U, infer V]
			? U
			: Elements extends readonly [infer U, ...infer V]
				// If we return `V[number] | U` directly, it would be wrong for `[[string, boolean, object, ...number[]]`.
				// So we need to recurse type `V` and carry over the type of the element before the spread element.
				? ArrayExceptLastElement<V, U>
				: Elements extends ReadonlyArray<infer U>
					? U | ElementBeforeTailingSpreadElement
					: never;

I had use for it in a string manipulation function where I used it to remove the last .${string} part in pathnames. Is it worth it for me to write a pull request for this ?

Superpat avatar Apr 26 '24 17:04 Superpat

You can use ArraySlice:

import type { ArraySlice } from 'type-fest'
type A = ArraySlice<[0, 1, 2, 3, 4], 0, -1>;
// => [0, 1, 2, 3]

Emiyaaaaa avatar Apr 29 '24 06:04 Emiyaaaaa

Oh I didnt realize you could use a negative index that way. Thanks !

Superpat avatar Apr 29 '24 15:04 Superpat

Reopening this, although it might be better as an actual bug report. ArraySplice is returning unknown[] where ArrayExceptLastElement was returning a more concrete type.

Meaning I was able to use Join on the output of ArrayExceptLastElement

Superpat avatar Apr 29 '24 19:04 Superpat

Can you provide a minimum reproduction?

Emiyaaaaa avatar Apr 29 '24 22:04 Emiyaaaaa

Here you go

Superpat avatar May 07 '24 14:05 Superpat

Here you go

ArraySlice, not ArraySplice

Emiyaaaaa avatar May 08 '24 07:05 Emiyaaaaa

Oh, I feel dumb. ArraySlice works as intended, sorry for the mistake.

Superpat avatar May 09 '24 02:05 Superpat