Last active
May 19, 2019 04:11
-
-
Save zapkub/c64225ddd1e49211ab300569ece2c144 to your computer and use it in GitHub Desktop.
Empty checking with type guard
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 { 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