首页 > 解决方案 > 元素隐式具有“任何”类型,因为索引表达式不是“数字”类型。ts(7015)

问题描述

打字稿新手在这里。我在reduce 数组方法中的“日期”下收到上述错误。我知道我需要将日期声明为数字而不是字符串,但不确定如何/在哪里?

提前致谢!

const dates = log?.reduce((dates, order) => {
const date = dateFormat(order.updated_at);
if (!dates[date]) {
  dates[date] = [];
}
dates[date].push(order);
return dates },[])

标签: javascriptarraystypescriptreduce

解决方案


Based on your code, order seems to be some object with a property updated_at that seems to be a number. In the loop, you format this number into a string and use it to index an object dates so that you end up with a mapping of dates to orders on that date.

In Typescript, a map/dictionary are formally called a Record and is normally written as Record<TypeOfKey, TypeOfValue> to denote a map of TypeOfKey to TypeOfValue. In older code, you may encounter the old (but still valid) way of defining a record that looks like { [key: TypeOfKey]: TypeOfValue }. The most basic Record is a Record<string, any>, an object that you can put any data on as long as the property is a string.

Assuming the type of your order object is an interface called Order, similar to:

interface Order {
  updated_at: number;
  /* ... other props ... */
}

You would need dates to be a Record<string, Order[]> (a map with a string key that contains an array of Order objects). To apply this type to dates, you would assign it to the second argument of reduce() like so:

const dates = log?.reduce((dates, order) => {
  const date = dateFormat(order.updated_at);
  if (!dates[date]) {
    dates[date] = [];
  }
  dates[date].push(order);
  return dates;
}, {} as Record<string, Order[]>); // <-- gives "dates" this type

推荐阅读