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

ConditionalKeys does not correctly filter out never type #878

Closed
roryabraham opened this issue May 9, 2024 · 3 comments · Fixed by #881
Closed

ConditionalKeys does not correctly filter out never type #878

roryabraham opened this issue May 9, 2024 · 3 comments · Fixed by #881
Labels
bug Something isn't working help wanted Extra attention is needed

Comments

@roryabraham
Copy link
Contributor

roryabraham commented May 9, 2024

I'm seeing some unexpected behavior in this minimal example:

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}>;

The root cause is that never can extend anything. I'm not sure if this is expected behavior or not, but it was a gotcha for me. It can be fixed like so:

type ConditionalKeys<Base, Condition> = {
    [Key in keyof Base]-?:
        // The key is retained if its value extends the given `Condition` and is not `never`
        Base[Key] extends Condition
            ? (Base[Key] extends never ? never : Key)
            : never;
}[keyof Base];

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
@roryabraham
Copy link
Contributor Author

Happy to open a PR if we agree that this is unexpected behavior.

@sindresorhus
Copy link
Owner

That is indeed unexpected behavior. A pull request would be amazing 🙏

@roryabraham
Copy link
Contributor Author

Opened #881. Thanks in advance for reviewing 🙇🏼

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working help wanted Extra attention is needed
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants