Skip to content
This repository has been archived by the owner on Feb 16, 2021. It is now read-only.

Add RequiredKeys and OptionalKeys types #33

Merged
merged 2 commits into from
Nov 21, 2018
Merged

Add RequiredKeys and OptionalKeys types #33

merged 2 commits into from
Nov 21, 2018

Conversation

saitonakamura
Copy link
Contributor

@saitonakamura saitonakamura commented Nov 19, 2018

I've added RequiredKeys and OptionalKeys helpers that extract keys that either required or optional accordingly. It can be useful for example to produce a Record that saves optionality

type Foo = {
  x: string,
  a: number,
  y?: number,
  b?: string,
}

type RecordOptional<K extends keyof any, T> = {
  [P in K]?: T;
};

// Not a record to be fair, cause it accepts type instead of keyof
// but I haven't figured out a good name
type RecordWithSavingOptional<T1, T2> =
  Record<RequiredKeys<T1>, T2>
  & RecordOptional<OptionalKeys<T1>, T2>

// $ExpectError "a" is missing
const bar: RecordWithSavingOptional<A, Date> = { x: new Date() }

It also works only with known keys, because of the infer magic. I tried to use the same approach (adding [keyof T] to the end) as in KeysOfType to no avail, it gives me "a" | "b" | undefined for some reason.

Idea is taken from microsoft/TypeScript#12215 (comment) so kudos to @jcalz @ferdaber and @ajafff!

@saitonakamura
Copy link
Contributor Author

saitonakamura commented Nov 19, 2018

I'm gonna also add it to readme, but i'm not getting why dtslint formatting is complaining, i haven't even changed some of parts he's complaining about. And it doesn't complain locally. I believe the fact that i'm on windows to be the culprit, though i'm not sure how to fix it

@gcanti gcanti merged commit 747755c into gcanti:master Nov 21, 2018
@gcanti
Copy link
Owner

gcanti commented Nov 21, 2018

@saitonakamura nice, thanks!

@stefanobaghino
Copy link

This is very nice, thanks for contributing this @saitonakamura! Today I had a few issues trying to define a generic type with all the required keys in another, like in the following example:

type RequiredPart<A extends object> = Pick<A, RequiredKeys<A>>

I spotted what could have lead to the issue and hopefully solved it, I'd love to have your opinion on my PR.

@saitonakamura saitonakamura deleted the feat/required-optional-keys branch November 26, 2018 22:12
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants