How to handle ISO date strings in TypeScript?

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

提交回复
热议问题