Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ArrayExceptLastElement type #872

Closed
Superpat opened this issue Apr 26, 2024 · 7 comments
Closed

ArrayExceptLastElement type #872

Superpat opened this issue Apr 26, 2024 · 7 comments

Comments

@Superpat
Copy link

Superpat commented Apr 26, 2024

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 ?

@Emiyaaaaa
Copy link
Collaborator

You can use ArraySlice:

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

@Superpat
Copy link
Author

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

@Superpat Superpat reopened this Apr 29, 2024
@Superpat
Copy link
Author

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

@Emiyaaaaa
Copy link
Collaborator

Emiyaaaaa commented Apr 29, 2024

Can you provide a minimum reproduction?

@Superpat
Copy link
Author

Superpat commented May 7, 2024

Here you go

@Emiyaaaaa
Copy link
Collaborator

Here you go

ArraySlice, not ArraySplice

@Superpat
Copy link
Author

Superpat commented May 9, 2024

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

@Superpat Superpat closed this as completed May 9, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants