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.
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.
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.
You can use DateFromISOString
from io-ts-types
See it's documentation.