1

I have a method with the following signature

function unboxer(data, ...unbox) {
    return unbox.reduce((acc, key) => acc ? acc[key] : acc, data);
}

it will iteratively go over supplied keys in unbox array until value is unboxed. example:

unboxer({a: 'somevalue1', b: {c: 'somevalue2', d: {e: 'somevalue3'}}}, ['b', 'c'])

will return somevalue2

unboxer({a: 'somevalue1', b: {c: 'somevalue2', d: {e: 'somevalue3'}}}, ['a'])

will return somevalue1

what is the correct type for unbox parameter? I'd like to reflect that it contains iterative keyof values. Something along the lines of:

unboxer(data: T, unbox: [keyof T, keyof data[keyof T],keyof data[keyof data[keyof T]],.....]

however expression should create a connection between each level of unboxing keys. Meaning, for array ['a','e'] I should receive a compilation error for object:

{a: 'somevalue1', b: {c: 'somevalue2', d: {e: 'somevalue3'}}}
Noy Oliel
  • 1,430
  • 3
  • 13
  • 26
  • 1
    I believe that your question is a duplicate of one of these answers: [first - see second part of the answer](https://stackoverflow.com/questions/69449511/get-typescript-to-infer-tuple-parameters-types/69450150#69450150), [second](https://stackoverflow.com/questions/69449511/get-typescript-to-infer-tuple-parameters-types/69450150#69450150), [third](https://stackoverflow.com/questions/69126879/typescript-deep-keyof-of-a-nested-object-with-related-type#answer-69129328) and my [article](https://catchts.com/deep-pick) – captain-yossarian from Ukraine Jan 03 '22 at 08:22
  • If one of above answers work for you please let me know – captain-yossarian from Ukraine Jan 03 '22 at 08:22
  • 1
    You can use `Paths` from this answer https://stackoverflow.com/a/58436959/1113002 – Aleksey L. Jan 03 '22 at 09:14
  • @captain-yossarian, Thanks for the references. Yes, question is a duplication of the one referenced. I haven't checked whether solution works in my case yet but it seems to answer my question. – Noy Oliel Jan 08 '22 at 21:03

1 Answers1

0

Optional chaining should work, e.g. data?.b?.c

Alex Panchenko
  • 452
  • 2
  • 6