Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save charlypoly/cca52058705256009976287c98af6388 to your computer and use it in GitHub Desktop.
Save charlypoly/cca52058705256009976287c98af6388 to your computer and use it in GitHub Desktop.
TypeScript `instanceof` and `typeof`
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