sindresorhus / type-fest

A collection of essential TypeScript types
Creative Commons Zero v1.0 Universal
14.36k stars 545 forks source link

Optional Values of Type #68

Open WORMSS opened 5 years ago

WORMSS commented 5 years ago

Anyone know if its possible to get the Optional values of a type?

interface A {
  a: string;
  b?: string;
  c?:string;
  d: string;
}

type B = OptionalsOf<A>;

so B becomes something like

type B = {
  b?: string;
  c?: striing;
};

Though for my usecase I will do something like

type B = Required<OptionsOf<A>>;

But I presume that wouldn't make a difference?

Upvote & Fund

Fund with Polar

sindresorhus commented 4 years ago

What problem are you trying to solve? Why do you need to get the optionals?

WORMSS commented 4 years ago

Specifying what the optional defaults should be.

resynth1943 commented 4 years ago

@WORMSS You're probably looking for OptionalKeys, as discussed here https://github.com/sindresorhus/type-fest/issues/56#issuecomment-583733537

@sindresorhus Since this seems to be a valid use-case, how would we feel about PRing OptionalKeys in separately to #56?

resynth1943 commented 4 years ago

Also, as for specifying the defaults, if they're all the same, you can do this.

type AWithDefaults = Omit<A, OptionalKeys<A>> & Record<OptionalKeys<A>, Default>;
sindresorhus commented 4 years ago

Since this seems to be a valid use-case, how would we feel about PRing OptionalKeys in separately to #56?

Sure, but if we add OptionalKeys, we should probably also add RequiredKeys.

dcousens commented 4 years ago

+1 for OptionalKeys and RequiredKeys. I didn't mind the learning exercise before I found this ticket, but it would have been nice to have it in the library!

My solution was

type OptionalKeys <T> = {
  [K in keyof T]: Pick<Partial<T>, K> extends Pick<T, K> ? K : never
}[keyof T]

Happy to PR, but maybe @resynth1943's answer from #56: {} extends Pick<T, K> ? K : never is nicer.