javascript - 元素隐式具有“任何”类型,因为索引表达式不是“数字”类型。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 },[])
解决方案
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
推荐阅读
- excel - 根据标题值VBA重新排序列
- go - 选择阻塞的呼叫和频道
- python - setup.py find_packages() 未将软件包安装到 anaconda 环境
- r - 增加输入的德雷克计划工作流程
- c# - 在 Entity Framework Plus 中的 IncludeFilter 上使用 AND (&&) 运算符不会带回嵌套/子对象
- java - 我们如何在序列的警报对话框中显示选定的 ListView 项?
- ios - 在 SwiftUI 中更新路径
- c# - DbContext 获取
返回动态表 - node.js - 使用 Joi 验证密码
- web-scraping - 正在使用的 LinkedIn 访问令牌