Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save MrChocolatine/367fb2a35d02f6175cc8ccb3d3a20054 to your computer and use it in GitHub Desktop.
Save MrChocolatine/367fb2a35d02f6175cc8ccb3d3a20054 to your computer and use it in GitHub Desktop.

Revisions

  1. MrChocolatine renamed this gist Dec 3, 2022. 1 changed file with 0 additions and 0 deletions.
  2. MrChocolatine renamed this gist Dec 3, 2022. 1 changed file with 0 additions and 0 deletions.
  3. MrChocolatine revised this gist Oct 23, 2021. 1 changed file with 2 additions and 6 deletions.
    8 changes: 2 additions & 6 deletions ts-more_precise_toISOString.d.ts
    Original file line number Diff line number Diff line change
    @@ -1,12 +1,8 @@
    /**
    * A date in ISO 8601 format is returned
    * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
    */

    // In TS, interfaces are "open" and can be extended
    interface Date {
    /**
    * Give a more precise return type to the method `toISOString()`
    * 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;
    }
  4. MrChocolatine renamed this gist Oct 23, 2021. 1 changed file with 0 additions and 0 deletions.
  5. MrChocolatine created this gist Oct 23, 2021.
    39 changes: 39 additions & 0 deletions ts - accurate return type for `toISOString`.d.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@
    /**
    * A date in ISO 8601 format is returned
    * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
    */

    // In TS, interfaces are "open" and can be extended
    interface Date {
    /**
    * Give a more precise return type to the method `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`;