Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}, {})
like image 838
Igor Pavlenko Avatar asked Dec 13 '19 11:12

Igor Pavlenko


Video Answer


1 Answers

You can pass in the type as an argument to reduce:

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

See an example here: https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABAcwKZlQJwIZVQFRgFtUBJMPTAN2wBsBnACmwC4wQiAjLAGkU5aJ2XXogiDh3TAEpEAbwCwAKESJMqKCExIA2stWqAylEwwwyZtL7HT5xpyuIbZixGn7EAXWUBfZctoNNVR6EFooRABeFHQsXAJiMgosGgZGAAY+AEYAFhzMxABmdOkAOnUAExAIVAAeACVUCDhMCtr6Exc+DttkAD4+xmYICD5U2Ui++Q9sEZ1UzyjEVIBuD3VNbURZiDWlHz45H3clZWawejhA0to4CwAidVDw+74nsKhpIA

like image 184
caseyjhol Avatar answered Sep 22 '22 23:09

caseyjhol