Forked from MrChocolatine/TS - More precise return type method Date#toISOString.d.ts
Created
July 25, 2022 21:53
-
-
Save dantekelly/b010e84d330c54f81f8c17ff2f98583d to your computer and use it in GitHub Desktop.
TypeScript – How to accurately type dates in ISO 8601 format
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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`; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment