Robust JavaScript Type Detection

3.5.1 · maintenance · verified Sun Apr 19

type-of-is provides a reliable mechanism for JavaScript type detection and comparison, addressing the well-known quirks of the native `typeof` operator (e.g., `typeof null` being 'object', or arrays being 'object'). It uses a combination of `Object.prototype.toString` and constructor checks to determine the true type of a value, including primitives, built-in objects, and custom constructors. The package is currently at version 3.5.1, though the latest publicly listed version on npm (3.4.0) was published in February 2017, suggesting a very slow or effectively halted release cadence. Its key differentiator is its commitment to 'sensible / unsurprising' type results, making it suitable for validation and conditional logic where native `typeof` falls short. It offers functions like `Type.of` to get the constructor, `Type.string` for a string representation, and `Type.is` for comparison against a type or string.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates core type detection, string representation, and type comparison functionalities using both direct methods and the shorthand `Type()` function.

import Type from 'type-of-is';

// Determine type using Type.of() or Type(single_argument)
console.log('Type.of("hello"):', Type.of('hello')); // [Function: String]
console.log('Type(123):', Type(123));             // [Function: Number]
console.log('Type.of([]):', Type.of([]));           // [Function: Array]
console.log('Type.of(null):', Type.of(null));       // null
console.log('Type.of(undefined):', Type.of(undefined)); // undefined

// Get type as a string using Type.string()
console.log('Type.string("world"):', Type.string('world')); // "String"
console.log('Type.string({}):', Type.string({}));         // "Object"
console.log('Type.string(null):', Type.string(null));     // "null"

// Test if an object is of a specific type using Type.is() or Type(obj, type)
function CustomObject() {}
const myObj = new CustomObject();

console.log('Type.is(true, Boolean):', Type.is(true, Boolean)); // true
console.log('Type.is("test", "String"):', Type.is('test', 'String')); // true
console.log('Type.is(myObj, CustomObject):', Type.is(myObj, CustomObject)); // true
console.log('Type.is(myObj, Object):', Type.is(myObj, Object)); // false (Type.is checks direct constructor, not prototype chain by default)

// Type.instance() wraps instanceof
console.log('Type.instance(myObj, CustomObject):', Type.instance(myObj, CustomObject)); // true
console.log('Type.instance(myObj, Object):', Type.instance(myObj, Object));   // true

view raw JSON →