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

Fix ConditionalKeys - prevent never from being included unintentionally #881

Merged
merged 9 commits into from
May 25, 2024

Conversation

roryabraham
Copy link
Contributor

Fixes #878

The following minimal example doesn't work as expected with the minimal example, because it includes d in the result, even though the value is never

type ConditionalKeys<Base, Condition> =
{
	// Map through all the keys of the given base type.
	[Key in keyof Base]-?:
	// Pick only keys with types extending the given `Condition` type.
	Base[Key] extends Condition
	// Retain this key since the condition passes.
		? Key
	// Discard this key since the condition fails.
		: never;

	// Convert the produced object into a union type of the keys which passed the conditional test.
}[keyof Base];

type MyMap = {
	a: {
		b: string;
	};
	c: {
		html: string;
	};
	d: never;
};

type MyFilteredMap = ConditionalKeys<MyMap, {html: string}>;

@roryabraham
Copy link
Contributor Author

roryabraham commented May 23, 2024

The only thing that's a bit funky with this implementation is that it doesn't work if the condition you're trying to target is never. In this example, MyFilteredMap evaluates to never, not d:

type MyMap = {
	a: {
		b: string;
	};
	c: {
		html: string;
	};
	d: never;
};

type MyFilteredMap = ConditionalKeys<MyMap, never>;

@roryabraham
Copy link
Contributor Author

roryabraham commented May 23, 2024

Ok, updated it to work for targeting never as well. I feel like this is more how I'd expect it to work. I might also have use-cases for that actually 🤔

// Discard this key since the condition fails.
// Retain this key since the condition passes
?
// If the condition extends never, only include the key if the value for that key is also never
Copy link
Contributor Author

Choose a reason for hiding this comment

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

let me know if you want to format this differently. I chose to progressively increase indentation for each level of ternary, and to keep comments indented to the same level as the line they're describing.

@roryabraham

This comment was marked as outdated.

@roryabraham

This comment was marked as resolved.

@roryabraham

This comment was marked as outdated.

@roryabraham
Copy link
Contributor Author

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.

ConditionalKeys does not correctly filter out never type
2 participants