-
-
Notifications
You must be signed in to change notification settings - Fork 230
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
Support RequiredKeys and OptionalKeys #53
Comments
Looks useful, accepting PR's! Requirements:
If you want to introduce some helper types please keep them private |
I'd like to add type PickKeys<T extends object, TValue extends null | undefined> = NonNullable<
{ [K in keyof T]: TValue extends T[K] ? K : never }[keyof T]
>
type NullableKeys<T extends object> = PickKeys<T, null>
type OptionalKeys<T extends object> = PickKeys<T, undefined>
type RequiredKeys<T extends object> = Exclude<keyof T, OptionalKeys<T>> Playground (works only with strictNullChecks) |
@levenleven
What do you think? EDIT: We might add both if that make sense |
I think Now regarding names:
|
I agree we could greatly benefit from both general helpers and shortcuts. New API Proposal for extending Pick/Omit and Object-Keys Helpers... Moved to #59 |
I'm for |
I understand your semantics argument, but in reality Partial equals Optional. In general, I think Optional would be a better name and for that reason, the best would be to use OptionalKeys and create an alias (Optional) for Partial as well to keep the API consistent. |
I find a bug in the StackOverflow version. type KeysOfType<T, U> = { [K in keyof T]: T[K] extends U ? K : never }[keyof T];
type RequiredKeys<T> = Exclude<KeysOfType<T, Exclude<T[keyof T], undefined>>, undefined>;
type OptionalKeys<T> = Exclude<keyof T, RequiredKeys<T>>;
type Obj = {
a: any;
b?: string;
c?: boolean;
};
type A = RequiredKeys<Obj>; // "a" | "b" | "c"
type B = OptionalKeys<Obj>; // never |
And another issue is that how to handle Should its |
@piotrwitek I think it could be better if we create a new issue for the new API proposal ? |
@malash see above working version. Regarding |
type A = Required<{ a: number | undefined }>;
type B = Required<{ a?: number }>;
|
@malash interesting, seems you're right. We'll need to tweak Required/Optional resolution |
Depending on the implementation ( |
Yeah, now it makes much more sense to tackle RequiredKey/OptionalKeys separately from all the other helpers proposed here. All the others are still perfectly valid |
Right because I would argue that |
Demo:
https://stackoverflow.com/questions/53809467/typescript-how-get-optional-keys-of-type
EDIT1: Added edge cases
The text was updated successfully, but these errors were encountered: