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

feat(union-to-intersection): allow indexing by the resulting type #682

Merged
merged 1 commit into from
Oct 7, 2023

Conversation

niieani
Copy link
Contributor

@niieani niieani commented Sep 8, 2023

Previously, using UnionToIntersection in the key position would result in the error:

Type 'unknown' cannot be used as an index type.

type Objects = { a: string } | { b: string } | { c: string }
type X = Objects[UnionToIntersection<keyof Objects>]

After the change the error goes away, and it doesn't affect how the type works otherwise.
The use case is when you use generics and want to ensure the type is never for unions of objects.

@sindresorhus
Copy link
Owner

Can you add a test?

@sindresorhus
Copy link
Owner

@niieani Bump :)

@niieani
Copy link
Contributor Author

niieani commented Sep 26, 2023

Hi @sindresorhus, sorry I'm an OSS maintainer too, didn't yet have time to follow up. It's on my list.

@niieani niieani force-pushed the patch-2 branch 2 times, most recently from bb51015 to bb96e04 Compare October 7, 2023 01:01
test: ability to index T by UnionToIntersection<T>
@niieani
Copy link
Contributor Author

niieani commented Oct 7, 2023

Hi @sindresorhus! Added a test.

@sindresorhus sindresorhus merged commit 61f2ff9 into sindresorhus:main Oct 7, 2023
6 checks passed
@JGJP
Copy link

JGJP commented Jan 16, 2024

@niieani @sindresorhus

Sorry for bringing this up but why was this done? Why should you be able to pass a string to UnionToIntersection?

The example uses

type X = Objects[UnionToIntersection<keyof Objects>]

(keyof Objects actually resolves to never due to there being no keys in common)

but I believe that this would be closer to a real world usage?

type X = Objects[keyof UnionToIntersection<Objects>]

It seems that the issue of there being no keys in common was actually recognized, as the eventually added test includes the key z which is common between all objects:

// It's possible to index by the resulting type.
type ObjectsUnion = {a: string; z: string} | {b: string; z: string} | {c: string; z: string};
declare const value: ObjectsUnion[UnionToIntersection<keyof ObjectsUnion>];
expectType<string>(value);

In this test though UnionToIntersection<keyof ObjectsUnion> just evaluates to 'z', so UnionToIntersection is totally unnecessary.

@sindresorhus
Copy link
Owner

@JGJP It's generally better to open a new issue than to comment on an old pull request.

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.

3 participants