Created
November 29, 2021 10:56
-
-
Save charlypoly/cca52058705256009976287c98af6388 to your computer and use it in GitHub Desktop.
TypeScript `instanceof` and `typeof`
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
import { format as fmtDate, parseISO } from 'date-fns' | |
function formatDate(date: Date | string | number, format = 'dd-mm-YYYY') { | |
let d = null | |
if (typeof date === 'string') { | |
date | |
// `date` is of type `string` | |
d = parseISO(date) | |
} else if (typeof date === 'number') { | |
// `date` is of type `number` | |
d = new Date(date) | |
} else if (date instanceof Date) { | |
// `date` is of type `Date` | |
d = date | |
} else { | |
return null | |
} | |
if (d.toString() === 'Invalid Date') { | |
return null | |
} else { | |
return fmtDate(d, format) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment