How to handle ISO date strings in TypeScript?

后端 未结 3 941
无人共我
无人共我 2021-02-20 06:09

I\'m brand new to typescript, so I\'m trying to get the hang of it.

A network request is going to return a JSON object with a field in ISO Date string format.

         


        
3条回答
  •  渐次进展
    2021-02-20 06:52

    You can use a Type Guard.

    import moment from 'moment'
    
    export const isISO = (input: any): input is tISO =>
      moment(input, moment.ISO_8601, true).isValid()
    

    Then you can use whatever custom logic in your you want to handle any bad dates, e.g.:

    const maybeISO = fetch('Maybe ISO')
    
    if (isISO(maybeISO)) {
      // proceed
    } else {
      // check other format?
      // log error?
    }
    

    Cheers.

提交回复
热议问题