type-fest
type-fest copied to clipboard
ArrayExceptLastElement type
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 ?
You can use ArraySlice
:
import type { ArraySlice } from 'type-fest'
type A = ArraySlice<[0, 1, 2, 3, 4], 0, -1>;
// => [0, 1, 2, 3]
Oh I didnt realize you could use a negative index that way. Thanks !
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
Can you provide a minimum reproduction?
Oh, I feel dumb. ArraySlice works as intended, sorry for the mistake.