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: create AllUnionFields type #997

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

RebeccaStevens
Copy link
Contributor

@RebeccaStevens RebeccaStevens commented Dec 3, 2024

fix #996

TODO: Create a deep version of the type.

@Emiyaaaaa
Copy link
Collaborator

Is there a better name for it?

// @sindresorhus

Copy link
Contributor

@som-sm som-sm left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@RebeccaStevens IMO, the following implementation is simpler than the one proposed in this PR:

export type AllUnionFields<Union> = [Union] extends [NonRecursiveType | ReadonlyMap<unknown, unknown> | ReadonlySet<unknown> | UnknownArray]
	? Union
	: Simplify<
	SharedUnionFields<Union> &
	{
		readonly [P in ReadonlyKeysOfUnion<Union>]?: ValueOfUnion<Union, P>;
	} & {
		[P in Exclude<KeysOfUnion<Union>, ReadonlyKeysOfUnion<Union> | keyof Union>]?: ValueOfUnion<Union, P>;
	}
	>;

type ValueOfUnion<Union, Key> = Union extends unknown ? Key extends keyof Union ? Union[Key] : never : never;

type ReadonlyKeysOfUnion<T> = T extends unknown ? keyof {
	[P in keyof T as IsEqual<{[Q in P]: T[P]}, {readonly [Q in P]: T[P]}> extends true ? P : never]: never
} : never;

This passes all the existing test cases and also uses utilities like ValueOfUnion and ReadonlyKeysOfUnion, which can be exposed as standalone types.

WDYT?

@som-sm
Copy link
Contributor

som-sm commented Dec 9, 2024

And this would probably also need changes similar to this.

@RebeccaStevens
Copy link
Contributor Author

@som-sm I agree, that implementation is nicer. I pushed an update with that one.

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.

New Type: AllUnionFields (similar to SharedUnionFields)
3 participants