0

I want to create a function whose options parameter is used to determine the argument passed to its returned function once executed. I think this can be clearer showing my own code, where I'm building an object whose keys are the same than input ones but in upper case:

type IOptions<TA, TB, TC> = Partial<{ a: TA, b: TB, c: TC }>;

const createFun = <TA, TB, TC>(options: IOptions<TA, TB, TC>) => {
  type ITempA = TA extends undefined ? never : TA;
  type ITempB = TB extends undefined ? never : TB;
  type ITempC = TC extends undefined ? never : TC;
  return (fun: (args: { A: ITempA, B: ITempB, C: ITempC }) => void) => {
    fun({
      A: options.a as ITempA,
      B: options.b as ITempB,
      C: options.c as ITempC,
    });
  }
}

createFun({ a: { one: 1, two: 2 } })(args => { console.log(args.A.one) });
              //                       ^
              //                       |
              // Here `args` is as follows
              // { 
              //    A: {one: number; two: number}, 
              //    B: unknown, 
              //    C: unknown 
              // }

What I need is that args does not include any non-provided key. In this example I expect that args = { A: { one: 1, b: 2 } } so TypeScript complains in case I try to do read args.B.

NOTE I've tried to consider all combinations of existing keys inside options, to create an interface based on it, but it is a bad approach as that options object may be larger. I'm showing three items only (A, B, C) for simplification.

Thanks

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.