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

Add a ReadonlyKeys which finds readonly keys #211

Closed
voxpelli opened this issue May 19, 2021 · 2 comments · Fixed by #619
Closed

Add a ReadonlyKeys which finds readonly keys #211

voxpelli opened this issue May 19, 2021 · 2 comments · Fixed by #619
Labels
help wanted Extra attention is needed type addition

Comments

@voxpelli
Copy link
Collaborator

I needed to find out what keys that are assignable and remove all keys but those, but found no way in type-fest or stock typescript, but did stumble upon this trick from @mattmccutchen on Stack Overflow.

Making an issue here to keep track of this, if I get time later then I may wrap up a PR, else feel free to make one for this.

The example from Stack Overflow is:

// https://github.com/Microsoft/TypeScript/issues/27024#issuecomment-421529650
type IfEquals<X, Y, A, B> =
    (<T>() => T extends X ? 1 : 2) extends
    (<T>() => T extends Y ? 1 : 2) ? A : B;

// Alternatively:
/*
type IfEquals<X, Y, A, B> =
    [2] & [0, 1, X] extends [2] & [0, 1, Y] & [0, infer W, unknown]
    ? W extends 1 ? B : A
    : B;
*/

type WritableKeysOf<T> = {
    [P in keyof T]: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P, never>
}[keyof T];
@voxpelli
Copy link
Collaborator Author

voxpelli commented May 19, 2021

I did one minor addition when I used this in some code now:

I wrapped the result in NonNullable<>, as else, when at least all keys were optional, a undefined would be appended, and that would make Pick<> refuse it as an input:

export type WritableKeysOf<T> = NonNullable<{
    [P in keyof T]: IfEquals<
      { [Q in P]: T[P] },
      { -readonly [Q in P]: T[P] },
      P,
      never
    >
}[keyof T]>;

@sindresorhus
Copy link
Owner

👍 PR welcome.

@sindresorhus sindresorhus added the help wanted Extra attention is needed label May 19, 2021
kkmuffme added a commit to kkmuffme/type-fest that referenced this issue May 15, 2023
sindresorhus#211 + sindresorhus#616 + opposite since it's very similar and might be useful
kkmuffme added a commit to kkmuffme/type-fest that referenced this issue May 15, 2023
Close sindresorhus#211
Close sindresorhus#616
+ opposite since it's very similar and might be useful
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Extra attention is needed type addition
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants