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

Expose NonEmptyTuple #661

Closed
tommy-mitchell opened this issue Aug 5, 2023 · 3 comments · Fixed by #915
Closed

Expose NonEmptyTuple #661

tommy-mitchell opened this issue Aug 5, 2023 · 3 comments · Fixed by #915
Labels
help wanted Extra attention is needed type addition

Comments

@tommy-mitchell
Copy link
Contributor

tommy-mitchell commented Aug 5, 2023

Similar to #659, NonEmptyTuple is a convenient type to expose:

/**
Matches any non empty tuple.
*/
export type NonEmptyTuple = readonly [unknown, ...unknown[]];

We could augment it to accept a generic type argument:

type NonEmptyTuple<TupleType = unknown> = readonly [TupleType, ...TupleType[]];

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar
@sindresorhus
Copy link
Owner

PR welcome 👍

@sindresorhus
Copy link
Owner

We could augment it to accept a generic type argument:

👍

@sindresorhus sindresorhus added help wanted Extra attention is needed type addition labels Aug 5, 2023
@tommy-mitchell
Copy link
Contributor Author

tommy-mitchell commented Aug 5, 2023

Hm, maybe it's not such a good idea? You can't use array.length checks to guard against empty arrays, and sparse arrays add a lot of edge cases: microsoft/TypeScript#38000 (SO thread)

function printFirstElement<Tuple extends NonEmptyTuple>(tuple: Tuple) {
	console.log(tuple[0]);
}

printFirstElement(['a', 'b', 'c']);
//=> 'a'

printFirstElement([]);
//=> error TS2345: Argument of type '[]' is not assignable to parameter of type 'NonEmptyTuple'.

declare const arr: string[];

if (arr.length > 0) {
	printFirstElement(arr);
	//=> error TS2345: Argument of type 'string[]' is not assignable to parameter of type 'NonEmptyTuple'.
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Extra attention is needed type addition
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants