简体   繁体   中英

give type to accumulator with array reduce typescript

I am generating object with time intervals with some func, it returns ["00:00","00:30","01:00"] ... , but for my purpose i need to have obj-map {{"00:00": "00:00"}, {"00:30":"00:30"}, {"01:00":"01:00"}} I have trouble typing the reduce func below, how can i type acc or the return value of the func to avoid using any as type for acc ?

generateTimeIntervals(0, 1440, 30).reduce((acc, val) => {
  acc[val] = val;
  return acc;
}, {})

how can i type acc or the return value of the func to avoid using any as type for acc?

You'd do that by providing the type of the {} seed you're providing, for instance Record<string, string> (but the exact type isn't the point here, the point is that assigning a type is how you do what you asked):

let result = generateTimeIntervals(0, 1440, 30).reduce((acc, val) => {
  acc[val] = val;
  return acc;
}, {} as Record<string, string>)

TypeScript will be able to follow the reduce call's logic sufficiently to type the return value for you based on that.


It's not entirely clear to me from the question whether your reduce code also needs some tweaking, but that's a different question...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM