Typescript newbie here. I'm getting the above error under ' date ' within a reduce array method. I understand I need to declare date as a number instead of string, but unsure how/where?
Thanks in advance!
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
Since it cannot infer date
type it assumes that it is of any type.
You are trying also to access an array by index date
so it expects to be of type number so it can access by index.
You can either tell it the date is an integer but since that is probably not your use case you can tell it that your dates is a dictionary
Since I do not know your exact use case here is how you can tell a variable is a dict from string to number
dates: { [key: string]: number }
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.