Skip to content

Instantly share code, notes, and snippets.

@zapkub
Last active May 19, 2019 04:11
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 zapkub/c64225ddd1e49211ab300569ece2c144 to your computer and use it in GitHub Desktop.
Save zapkub/c64225ddd1e49211ab300569ece2c144 to your computer and use it in GitHub Desktop.
Empty checking with type guard
import { isNull } from 'util'
type Empty = null | undefined | 0 | false | ''
export function IsEmpty<T>(thing: T | undefined | null | 0 | false | ''): thing is Empty {
const undefinedOrNull = typeof thing === 'undefined' || thing === null
if (undefinedOrNull) {
return true
}
if (typeof thing === 'string' && thing.length === 0) {
return true
}
if (typeof thing === 'number') {
return thing === 0 || isNaN(thing)
}
if (typeof thing === 'boolean') {
return !thing
}
return false || isNull(thing)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment