Created
December 12, 2017 22:46
-
-
Save dphilipson/e62e894fabca8c614baffef9615d970b to your computer and use it in GitHub Desktop.
Branded strings that represent dates in TypeScript.
This file contains 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
enum DateStringBrand {} | |
export type DateString = string & DateStringBrand; | |
function of(date: string | number | Date): DateString { | |
// This branching needed to satisfy TypeScript. | |
const dateObject = | |
typeof date === "string" | |
? new Date(date) | |
: typeof date === "number" ? new Date(date) : new Date(date); | |
if (isNaN(+dateObject)) { | |
throw new Error(`Cannot create DateString from "${date}".`); | |
} else { | |
return dateObject.toISOString() as DateString; | |
} | |
} | |
function now(): DateString { | |
return of(Date.now()); | |
} | |
export const DateString = { of, now }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment