Skip to content

Instantly share code, notes, and snippets.

@jrobinsonc
Last active February 13, 2024 15:44
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 jrobinsonc/6fa4727e4079928d748c1252a350be05 to your computer and use it in GitHub Desktop.
Save jrobinsonc/6fa4727e4079928d748c1252a350be05 to your computer and use it in GitHub Desktop.
Type Guard Functions for Various Data Types
function isDefined<T>(arg: T | undefined | null): arg is T {
return arg !== undefined && arg !== null;
}
/**
* Checks if the given argument is empty.
*
* ⚠️ Note that this values are not considered empty:
* - Boolean arguments
* - The number zero "0"
*
* @param arg - The argument to check.
* @returns `true` if the argument is empty, `false` otherwise.
*/
function isEmpty(arg: unknown): boolean {
if (typeof arg === "boolean") {
return false;
}
if (arg === undefined || arg === null) {
return true;
}
if (typeof arg === "string") {
return arg.trim().length === 0;
}
if (typeof arg === "number") {
return isNaN(arg);
}
if (Array.isArray(arg)) {
return arg.length === 0;
}
if (arg instanceof Map || arg instanceof Set) {
return arg.size === 0;
}
if (typeof arg === "object") {
return Object.keys(arg).length === 0;
}
throw new Error(`Argument could not be parsed: ${String(arg)}`);
}
/**
* Checks if a value is null or undefined.
*
* @param value - The value to check.
* @returns `true` if the value is null or undefined; otherwise, return `false`.
*/
function isNil(arg: unknown): arg is null | undefined {
return arg === null || arg === undefined;
}
/**
* This function checks if the given argument is a plain object or not.
*
* @template T - This is the type parameter, which defaults to `Record<string, unknown>`.
* @param arg - The argument that needs to be checked.
* @returns `true` if the argument is a plain object, `false` otherwise.
*/
function isPlainObject<T = Record<string, unknown>>(arg: unknown): arg is T {
return typeof arg === 'object' && arg !== null;
}
function isStringifiable(arg: unknown): arg is string | number | boolean | null | { toString(): string } {
return (
typeof arg === 'string' ||
typeof arg === 'number' ||
typeof arg === 'boolean' ||
arg === null ||
(typeof arg === 'object' && arg !== null && typeof arg.toString === 'function')
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment