[英]Accessing a Date array with TypeScript
我正在尝试访问 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
来获取开始和结束日期,然后我使用 function 来格式化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) ]
您在箭头 function 中将第一个参数的类型设置为Date
。
const addDate = (date: Date) => { // ...
当您尝试将其作为数组访问时,TS 将(正确地)抛出错误。
如果正在传递具有一个或多个日期的数组,则应相应地更新类型。 [Date, ...Date[]]
我用这个修复了它:
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')
})
}
所以我使用 moment.js 库来简化并将日期 object 转换为字符串,一切正常。 TypeScript 对将Array of dates
作为单个Date
类型感到满意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.