type-fest icon indicating copy to clipboard operation
type-fest copied to clipboard

Optional Values of Type

Open WORMSS opened this issue 4 years ago • 6 comments

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?

WORMSS avatar Oct 30 '19 08:10 WORMSS

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

sindresorhus avatar Nov 26 '19 10:11 sindresorhus

Specifying what the optional defaults should be.

WORMSS avatar Nov 26 '19 11:11 WORMSS

@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 avatar Feb 11 '20 22:02 resynth1943

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

resynth1943 avatar Feb 11 '20 22:02 resynth1943

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.

sindresorhus avatar Feb 16 '20 15:02 sindresorhus

+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.

dcousens avatar Jul 03 '20 02:07 dcousens