0

There is a type from a 3rd party:

interface UpdateRequest {
  data?: ValueRange[];
  options?: Options
}

I want to create a method with this signature:

update(params: RequiredOnly<UpdateRequest, 'data'>) {
  //...
}

The RequiredOnly type utility will make only the key 'data' is required, not both 'data' and 'options' like what Required does.

Is it possible to create that RequiredOnly type utility?

I'm stucking here:

type RequiredOnly<T, a extends keyof T> = { 
  [K in keyof T extends a ? a : never ]-?: T[K] 
} 
San Nguyen
  • 128
  • 1
  • 7

1 Answers1

6

You can use Pick and Required and intersect back with the original type to get back the other optional properties

type RequireSome<T, K extends keyof T> = Required< Pick<T, K>> & T;
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
  • This is clever, I like it. It still feels like jumping through hoops for no particular gain, but at least it works. :) +1 – João Mendes Mar 08 '19 at 17:11
  • 1
    @JoãoMendes mapped types let us apply the same transformation to all properties... That is why some jumping is required – Titian Cernicova-Dragomir Mar 08 '19 at 17:22
  • What if the given property is marked as undefined | null? And we want to make it neither undefined nor null? Could this solution easily be extended to remove null values as well as undefined? – ZenVentzi Apr 14 '19 at 14:07
  • 1
    @ZenVentzi This just removes the optionality, we can create a type that removes `undefined | null` as well but that is a different type, and a different question. Comments are a bad place for a lot of code or explanations, ask a question and I or someone else will answer. – Titian Cernicova-Dragomir Apr 14 '19 at 15:04