1

I need to narrow down types based on dynamic keys:

type Responses = {http1: HttpResponse, http2: Http2Response};
const responses = {http1: {body,header}, http2: {body,header}};
const [bodies,headers]=(["body","header"] as const).map(field=>
  Object.entries(responses).reduce((narrow,[key,value])=>
  Object.assign(narrow,{[key]:value[field]}),
  {} as {[key in keyof Responses]: responses[key][typeof field]})
);
// body = {http1: {body}, http2: {body}};
// header = {http1: {header}, http2: {header}};

but the value types end up being {http1: any, http2: any} instead of the respective Body and Header (not even Body|Header, even though that should be inferred by the indexed accesses, 'typeof field' being "body"|"header").

A simpler case would be simply inferring the type of mapped keys:

const [a,b]=(["body","header"] as const).map(field=>response[field]);

It results in union types (like Body|Header), instead of access types corresponding to the tuple indexes.

How to specify an indexed access type with dynamic keys?

Seems like an achievable inference, and would often spare a lot of redundant imperative declarations.

bpstrngr
  • 339
  • 3
  • 13
  • 1
    Your code isn't a [mre] (I don't know what `Http2Response` is for example), but if I understand the question properly: no, this is not possible in TypeScript, which lacks the ability to express that `map()` should be able to turn a tuple into another tuple where the type of each tuple element in the output is programmatically determined by the type of the corresponding input element, even if the callback is generic. [See the linked question/answer](https://stackoverflow.com/q/66091118/2887218) for more information. – jcalz Nov 14 '22 at 17:21
  • @jcalz yeah, i already tried to generalize to something more common, the HttpResponses weren't my actual types, but guess i should've just written Type1 Type2. perhaps i'll edit accordingly. Thanks for the detailed answer! i think i'll leave this question up cuz it's a more colloquial entry to the linked question and answer. – bpstrngr Nov 15 '22 at 21:25

0 Answers0