'Accessing a Date array with TypeScript
I am trying to access an array of dates in TypeScript, something that worked fine in normal JavaScript, but now I am having this error:
Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'Date'. Property '0' does not exist on type 'Date'.ts(7053)
So in React I use react-calendar to get an start and an end date, then I use a function to format the array of Dates
import React from 'react'
import Calendar from 'react-calendar'
export const Main = () => {
const [newDate, setDate] = useState<Date>(new Date())
const addDate = (date: Date) => {
setDate(date)
const formatDate = (input: Date[]) => {
// Convert month to number
const getMonthFromString = (mon: string) => {
return new Date(Date.parse(mon + ' 1, 2012')).getMonth() + 1
}
const parts = input.toString().split(' ')
const month = getMonthFromString(parts[1])
return `${month < 10 ? '0' + month : month}/${parts[2]}/${parts[3]}`
}
// It fails here, cannot get 0 index of date array
console.log(date[0])
}
return (
<Calendar
showNavigation={true}
minDate={new Date(2019, 0, 1)}
selectRange={true}
value={newDate}
onChange={addDate}
/>
)
}
When I log the date only I can see it is indeed an Array, before in JS I could just take the 0 and 1 index but not with TypeScript.
Array [ Date Tue Feb 01 2022 00:00:00 GMT+0000 (Greenwich Mean Time), Date Thu Feb 03 2022 23:59:59 GMT+0000 (Greenwich Mean Time) ]
Solution 1:[1]
You're setting the first parameter's type to Date in your arrow function.
const addDate = (date: Date) => { // ...
TS will (rightfully) throw an error when you try to access it as an array.
If an array with one or more dates is being passed you should update the type accordingly.
const addDate = (date: [Date, Date]) => { // ...
Solution 2:[2]
I fixed it with this:
import moment from 'moment'
...
const [dates, setDates] = useState<Date>=(new Date())
const [apidates, setApiDates] = useState<ApiProps>({
startDate: '',
endDate: ''
})
// Listen for calendar changes
const addDate = (date: Date) => {
setDate(date)
const dateArray = date.toString().split(',')
// Format the date for Google Search Console API YYYY-MM-DD
setApiDates({
...apidates,
startDate: moment(dateArray[0]).format('YYYY-MM-DD'),
endDate: moment(dateArray[1]).format('YYYY-MM-DD')
})
}
So I am using the moment.js library to simplify and by converting the date object to string, all works. TypeScript sees to be happy with an Array of dates objects as a single Date type.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Ãlvaro |
