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.
data : Data = {when: "2016-07-13T18:46:01.933Z"}
When I create the type signature for this interface, is there any way of specifying that this is actually an ISO timestamp or do I just have to use string?
interface Data {
when: string
}
I found out I could use a type alias which mentally helps, but doesn't really validate the ISO string.
type iso = string
interface Data {
when: iso
}
On a similar vein, I'm curious if there's anyway to generate js validation from these typescript annotations so I can validate the information received by the endpoint, otherwise the rest of my typed application is worthless.
If this is possible then it would be really cool if this iso string could be coerced into an actual Date object.
As I said, I'm new to typescript, so I'm not sure if this is beyond the scope of what typescript is supposed to do.
// In TS, interfaces are "open" and can be extended
interface Date {
/**
* Give a more precise return type to the method `toISOString()`:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
*/
toISOString(): TDateISO;
}
type TYear = `${number}${number}${number}${number}`;
type TMonth = `${number}${number}`;
type TDay = `${number}${number}`;
type THours = `${number}${number}`;
type TMinutes = `${number}${number}`;
type TSeconds = `${number}${number}`;
type TMilliseconds = `${number}${number}${number}`;
/**
* Represent a string like `2021-01-08`
*/
type TDateISODate = `${TYear}-${TMonth}-${TDay}`;
/**
* Represent a string like `14:42:34.678`
*/
type TDateISOTime = `${THours}:${TMinutes}:${TSeconds}.${TMilliseconds}`;
/**
* Represent a string like `2021-01-08T14:42:34.678Z` (format: ISO 8601).
*
* It is not possible to type more precisely (list every possible values for months, hours etc) as
* it would result in a warning from TypeScript:
* "Expression produces a union type that is too complex to represent. ts(2590)
*/
type TDateISO = `${TDateISODate}T${TDateISOTime}Z`;
The source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With