简体   繁体   English

使用 TypeScript 访问日期数组

[英]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:我正在尝试访问 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)

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所以在 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}
    />
  )
}

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.当我只记录日期时,我可以看到它确实是一个数组,在 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) ]

You're setting the first parameter's type to Date in your arrow function.您在箭头 function 中将第一个参数的类型设置为Date

const addDate = (date: Date) => { // ...

TS will (rightfully) throw an error when you try to access it as an array.当您尝试将其作为数组访问时,TS 将(正确地)抛出错误。

If an array with one or more dates is being passed you should update the type accordingly.如果正在传递具有一个或多个日期的数组,则应相应地更新类型。 [Date, ...Date[]]

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.所以我使用 moment.js 库来简化并将日期 object 转换为字符串,一切正常。 TypeScript sees to be happy with an Array of dates objects as a single Date type. TypeScript 对将Array of dates作为单个Date类型感到满意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM