Skip to content

Instantly share code, notes, and snippets.

@dphilipson
Created December 12, 2017 22:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dphilipson/e62e894fabca8c614baffef9615d970b to your computer and use it in GitHub Desktop.
Save dphilipson/e62e894fabca8c614baffef9615d970b to your computer and use it in GitHub Desktop.
Branded strings that represent dates in TypeScript.
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