我正在尝试访问 TypeScript 中的日期数组,这在普通 JavaScript 中运行良好,但现在我遇到了这个错误:
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)
所以在 React 中我react-calendar
用来获取开始和结束日期,然后我使用一个函数来格式化数组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}
/>
)
}
当我只记录日期时,我可以看到它确实是一个数组,之前在 JS 中我可以只取 0 和 1 索引,但不能使用 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) ]