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

ArrayTail: Fix support for optional parameters #977

Merged
merged 2 commits into from
Dec 2, 2024

Conversation

ferferga
Copy link
Contributor

@ferferga ferferga commented Nov 7, 2024

Fixes #978

@ferferga

This comment was marked as outdated.

@som-sm
Copy link
Collaborator

som-sm commented Nov 30, 2024

@ferferga Following solution addresses the issue mentioned in #978 while ensuring all existing tests continue to pass.

export type ArrayTail<TArray extends UnknownArrayOrTuple> = keyof TArray & `${number}` extends never
	? []
	: TArray extends readonly [unknown?, ...infer Tail]
		? Tail
		: [];

The conditional keyof TArray & `${number}` extends never is to separate tuples from empty arrays and non-tuple arrays like string[], so that we can handle them independently.


However, the updated implementation fails when the type is instantiated with unions. For example, TArray<[1, 2] | []> now incorrectly resolves to [] instead of the expected [2] | [] (although currently there’s no test covering this behaviour). To ensure the type continues to work correctly with unions, we can simply reorder the conditionals.

export type ArrayTail<TArray extends UnknownArrayOrTuple> = TArray extends readonly [unknown?, ...infer Tail]
	? keyof TArray & `${number}` extends never
		? []
		: Tail
	: [];

ferferga and others added 2 commits December 2, 2024 11:35
Co-Authored-By: som-sm <som-sm@users.noreply.github.com>
@ferferga
Copy link
Contributor Author

ferferga commented Dec 2, 2024

@som-sm Thank you very much for your input, works flawlessly! Added you as a co-author and took the chance to also add some tests.

@sindresorhus sindresorhus merged commit f6b1387 into sindresorhus:main Dec 2, 2024
11 checks passed
@sindresorhus sindresorhus changed the title fix(ArrayTail): not working with optional parameters ArrayTail: Fix support for optional parameters Dec 2, 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

Successfully merging this pull request may close these issues.

ArrayTail doesn't work when mixed with optional elements
3 participants