簡體   English   中英

使用 TypeScript 訪問日期數組

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM