CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-is-what

JavaScript and TypeScript type checking utility functions providing precise type validation with automatic type narrowing.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

builtin-types.mddocs/

Built-in Object Detection

Type checking functions for JavaScript built-in objects and browser/Node.js specific types. These functions detect standard JavaScript objects and platform-specific types.

Capabilities

Date Object Detection

Returns whether the payload is a Date instance.

/**
 * Returns whether the payload is a Date instance and is a valid date
 * (not Invalid Date). Uses both type checking and date validity validation.
 * @param payload - Value to check
 * @returns Type guard indicating if payload is a valid Date
 */
function isDate(payload: unknown): payload is Date;

Usage Examples:

import { isDate } from "is-what";

isDate(new Date()); // true
isDate(new Date("2023-01-01")); // true
isDate(new Date("invalid")); // false (Invalid Date)
isDate(Date.now()); // false (number timestamp)
isDate("2023-01-01"); // false (string)
isDate({}); // false

if (isDate(value)) {
  // TypeScript knows value is Date
  console.log(value.getFullYear());
  console.log(value.toISOString());
}

// Practical usage
function formatDate(input: unknown) {
  if (isDate(input)) {
    return input.toLocaleDateString();
  }
  throw new Error("Input must be a Date object");
}

Error Object Detection

Returns whether the payload is an Error instance.

/**
 * Returns whether the payload is an Error instance. Uses both type checking
 * and instanceof validation for comprehensive Error detection.
 * @param payload - Value to check
 * @returns Type guard indicating if payload is Error
 */
function isError(payload: unknown): payload is Error;

Usage Examples:

import { isError } from "is-what";

isError(new Error("test")); // true
isError(new TypeError("test")); // true
isError(new RangeError("test")); // true
isError({ message: "error" }); // false (error-like object)
isError("Error: something"); // false (string)

// Error handling
function handleResult(result: unknown) {
  if (isError(result)) {
    console.error("Operation failed:", result.message);
    console.error("Stack:", result.stack);
    return null;
  }
  
  return result;
}

// Type-safe error checking
function processWithErrorHandling(operation: () => unknown) {
  try {
    return operation();
  } catch (error) {
    if (isError(error)) {
      // TypeScript knows error is Error
      return { success: false, error: error.message };
    }
    
    // Handle non-Error throws
    return { success: false, error: "Unknown error occurred" };
  }
}

RegExp Detection

Returns whether the payload is a RegExp instance.

/**
 * Returns whether the payload is a RegExp instance
 * @param payload - Value to check
 * @returns Type guard indicating if payload is RegExp
 */
function isRegExp(payload: unknown): payload is RegExp;

Usage Examples:

import { isRegExp } from "is-what";

isRegExp(/abc/); // true
isRegExp(new RegExp("abc")); // true
isRegExp("/abc/"); // false (string)
isRegExp({}); // false

if (isRegExp(pattern)) {
  // TypeScript knows pattern is RegExp
  console.log(pattern.test("abc"));
  console.log(pattern.source);
  console.log(pattern.flags);
}

// Pattern validation
function validatePattern(input: unknown) {
  if (isRegExp(input)) {
    return { valid: true, pattern: input };
  }
  
  return { valid: false, error: "Must be a regular expression" };
}

Map Detection

Returns whether the payload is a Map instance.

/**
 * Returns whether the payload is a Map instance
 * @param payload - Value to check
 * @returns Type guard indicating if payload is Map
 */
function isMap(payload: unknown): payload is Map<unknown, unknown>;

Usage Examples:

import { isMap } from "is-what";

isMap(new Map()); // true
isMap(new Map([["a", 1], ["b", 2]])); // true
isMap({}); // false (plain object)
isMap(new Set()); // false (Set, not Map)

if (isMap(collection)) {
  // TypeScript knows collection is Map
  console.log(collection.size);
  collection.set("key", "value");
  console.log(collection.get("key"));
}

// Map processing
function processMapData(input: unknown) {
  if (isMap(input)) {
    const entries = Array.from(input.entries());
    return entries.map(([key, value]) => ({ key, value }));
  }
  
  return null;
}

Set Detection

Returns whether the payload is a Set instance.

/**
 * Returns whether the payload is a Set instance
 * @param payload - Value to check
 * @returns Type guard indicating if payload is Set
 */
function isSet(payload: unknown): payload is Set<unknown>;

Usage Examples:

import { isSet } from "is-what";

isSet(new Set()); // true
isSet(new Set([1, 2, 3])); // true
isSet([]); // false (array)
isSet(new Map()); // false (Map, not Set)

if (isSet(collection)) {
  // TypeScript knows collection is Set
  console.log(collection.size);
  collection.add("new item");
  console.log(collection.has("item"));
}

// Set operations
function convertToArray(input: unknown) {
  if (isSet(input)) {
    return Array.from(input);
  }
  
  throw new Error("Input must be a Set");
}

WeakMap Detection

Returns whether the payload is a WeakMap instance.

/**
 * Returns whether the payload is a WeakMap instance
 * @param payload - Value to check
 * @returns Type guard indicating if payload is WeakMap
 */
function isWeakMap(payload: unknown): payload is WeakMap<object, unknown>;

Usage Examples:

import { isWeakMap } from "is-what";

isWeakMap(new WeakMap()); // true
isWeakMap(new Map()); // false (Map, not WeakMap)
isWeakMap({}); // false

const obj = {};
if (isWeakMap(weakRef)) {
  // TypeScript knows weakRef is WeakMap
  weakRef.set(obj, "associated data");
  console.log(weakRef.get(obj));
}

WeakSet Detection

Returns whether the payload is a WeakSet instance.

/**
 * Returns whether the payload is a WeakSet instance
 * @param payload - Value to check
 * @returns Type guard indicating if payload is WeakSet
 */
function isWeakSet(payload: unknown): payload is WeakSet<object>;

Promise Detection

Returns whether the payload is a Promise instance.

/**
 * Returns whether the payload is a Promise instance
 * @param payload - Value to check
 * @returns Type guard indicating if payload is Promise
 */
function isPromise(payload: unknown): payload is Promise<unknown>;

Usage Examples:

import { isPromise } from "is-what";

isPromise(Promise.resolve(1)); // true
isPromise(new Promise(resolve => resolve(1))); // true
isPromise(async function() {}()); // true (async functions return promises)
isPromise({ then: () => {} }); // false (thenable, but not Promise)
isPromise("promise"); // false

// Async handling
async function handleAsyncResult(result: unknown) {
  if (isPromise(result)) {
    // TypeScript knows result is Promise
    try {
      const resolved = await result;
      return { success: true, data: resolved };
    } catch (error) {
      return { success: false, error };
    }
  }
  
  // Synchronous result
  return { success: true, data: result };
}

// Promise detection in utilities
function maybeAwait(value: unknown) {
  if (isPromise(value)) {
    return value; // Return the promise to be awaited
  }
  
  return Promise.resolve(value); // Wrap non-promise in resolved promise
}

Browser-Specific Types

Blob Detection

Returns whether the payload is a Blob instance (browser environments).

/**
 * Returns whether the payload is a Blob instance
 * @param payload - Value to check
 * @returns Type guard indicating if payload is Blob
 */
function isBlob(payload: unknown): payload is Blob;

File Detection

Returns whether the payload is a File instance (browser environments).

/**
 * Returns whether the payload is a File instance
 * @param payload - Value to check
 * @returns Type guard indicating if payload is File
 */
function isFile(payload: unknown): payload is File;

Usage Examples:

import { isBlob, isFile } from "is-what";

// Browser environment
if (typeof Blob !== 'undefined') {
  const blob = new Blob(['content'], { type: 'text/plain' });
  isBlob(blob); // true
  
  // File extends Blob
  const file = new File(['content'], 'test.txt', { type: 'text/plain' });
  isFile(file); // true
  isBlob(file); // true (File extends Blob)
}

// File upload handling
function handleFileUpload(input: unknown) {
  if (isFile(input)) {
    // TypeScript knows input is File
    return {
      name: input.name,
      size: input.size,
      type: input.type,
      lastModified: input.lastModified
    };
  }
  
  if (isBlob(input)) {
    // TypeScript knows input is Blob
    return {
      size: input.size,
      type: input.type
    };
  }
  
  throw new Error("Input must be a File or Blob");
}

Combined Built-in Type Patterns

import { 
  isDate, 
  isError, 
  isRegExp, 
  isMap, 
  isSet, 
  isPromise 
} from "is-what";

function analyzeBuiltinType(value: unknown) {
  if (isDate(value)) {
    return `Date: ${value.toISOString()}`;
  }
  
  if (isError(value)) {
    return `Error: ${value.message}`;
  }
  
  if (isRegExp(value)) {
    return `RegExp: ${value.source} (flags: ${value.flags})`;
  }
  
  if (isMap(value)) {
    return `Map with ${value.size} entries`;
  }
  
  if (isSet(value)) {
    return `Set with ${value.size} items`;
  }
  
  if (isPromise(value)) {
    return "Promise (pending/resolved/rejected)";
  }
  
  return "Not a recognized built-in type";
}

// Collection utilities
function processCollection(collection: unknown) {
  if (isMap(collection)) {
    return {
      type: "Map",
      size: collection.size,
      entries: Array.from(collection.entries())
    };
  }
  
  if (isSet(collection)) {
    return {
      type: "Set",
      size: collection.size,
      values: Array.from(collection.values())
    };
  }
  
  return null;
}

// Example usage
analyzeBuiltinType(new Date()); // "Date: 2023-01-01T00:00:00.000Z"
analyzeBuiltinType(/abc/g); // "RegExp: abc (flags: g)"
analyzeBuiltinType(new Map([["a", 1]])); // "Map with 1 entries"
analyzeBuiltinType(new Error("test")); // "Error: test"

docs

advanced-types.md

array-types.md

basic-types.md

builtin-types.md

generic-utils.md

index.md

number-validation.md

object-types.md

string-types.md

tile.json