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

Creating an exhaustive array from a union type #713

Open
gxxcastillo opened this issue Oct 18, 2023 · 2 comments
Open

Creating an exhaustive array from a union type #713

gxxcastillo opened this issue Oct 18, 2023 · 2 comments

Comments

@gxxcastillo
Copy link

gxxcastillo commented Oct 18, 2023

Say I have:

type T = 'one' | 'two' | 'three'

It would be great to generate a type, E that requires all union values, which in this case would be something like this but without enforcing order:

type E = ['one', 'two', 'three']

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
@fregante
Copy link
Collaborator

What for?

without enforcing order

I don’t think that's possible, the type you suggested is a tuple, which is ordered. I suppose extends can be used to build a type like if x[0] is 'one', then x[1] must be 'two' | 'three', but that sounds extremely verbose and complex.

@sindresorhus
Copy link
Owner

I think you could use the #686 type for this when it lands.

Untested ChatGPT generated:

type T = 'one' | 'two' | 'three';

type AllMembersPresent<Union> = UnionToTuple<Union> extends infer Array
	? (Array extends UnionToTuple<Union>
		? (Union extends Array[number] ? Array : never)
		: never)
	: never;

type E = AllMembersPresent<T>;

const validArray: E = ['one', 'three', 'two']; // This is valid
const invalidArray1: E = ['one', 'three'];     // This will throw a type error
const invalidArray2: E = ['one', 'three', 'four']; // This will throw a type error

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants