Skip to content

Instantly share code, notes, and snippets.

@marcolink
Last active October 1, 2021 14:23
Show Gist options
  • Save marcolink/a66bd4f9b354abc0081a5c166c2e5a59 to your computer and use it in GitHub Desktop.
Save marcolink/a66bd4f9b354abc0081a5c166c2e5a59 to your computer and use it in GitHub Desktop.
Typescript - Typed date strings using template string literal.
/**
* @desc range 0 - 9
*/
type Digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
export declare namespace ISO8601 {
/**
* @desc range 00 - 24
*/
type TimeHour = `${'0' | '1' | '2'}${'0' | '1' | '2' | '3' | '4'}`
/**
* @desc range 00 - 59
*/
type TimeMinute = `${0 | 1 | 2 | 3 | 4 | 5}${Digit}`
/**
* @desc range 00 - 59
*/
type TimeSecond = `${0 | 1 | 2 | 3 | 4 | 5}${Digit}`
/**
* @desc range 00 - 29
*/
type DateCentury = `${'0' | '1' | '2'}${Digit}`
/**
* @desc range 0 - 9
*/
type DateDecade = `${Digit}`
/**
* @desc range 0-9
*/
type DateSubDecade = `${Digit}`
/**
* @desc range 00 - 99
*/
type DateYear = `${DateDecade}${DateSubDecade}`
/**
* @desc range 0000 - 2999
*/
type DateYearFull = `${DateCentury}${DateYear}`
/**
* @desc range from 01 - 12
*/
type DateMonth = `${'01' | '02' | '03' | '04' | '05' | '06' | '07' | '08' | '09' | '10' | '11' | '12'}`
/**
* @desc range 0000-01 - 2999-12
*/
type DateYearAndMonth = `${DateYearFull}-${DateMonth}`
}
// Example
const date: ISO8601.DateYearAndMonth = '1980-02'
@marcolink
Copy link
Author

A Simple version (without full editor support) would be:

type Date = `${number}-${number}-${number}T${number}:${number}:${number}Z`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment