How to handle ISO date strings in TypeScript?

后端 未结 3 940
无人共我
无人共我 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.

    0 讨论(0)
  • 2021-02-20 07:02

    No this is not possible. For javascript there's nothing to do with typescript's interfaces. (JS is not generated at all for interfaces). Also all the type checks are done at "compile" or "transpile" time, not at run time.

    What you can do, is to use reviver function when parsing json. For example:

    const datePattern = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/;
    const json = '{"when": "2016-07-13T18:46:01.933Z"}';
    
    const result = JSON.parse(json, (key: any, value: any) => {
        const isDate = typeof value === 'string' && datePattern.exec(value);
        return isDate? new Date(value) : value;
    });
    

    Also you can identify Date property by key and in case it doesn't match the date pattern you could throw an error or do whatever you want.

    0 讨论(0)
  • 2021-02-20 07:07

    You can use DateFromISOString from io-ts-types See it's documentation.

    0 讨论(0)
提交回复
热议问题