typeOf
The typeOf utility returns a lowercase string representing the precise type of a value. It provides more detailed and accurate results than the native typeof operator, correctly identifying arrays, null, and other built-in objects.
Implementation
View Source Code
ts
export type ArgType =
| 'array'
| 'boolean'
| 'date'
| 'error'
| 'function'
| 'map'
| 'nan'
| 'null'
| 'number'
| 'object'
| 'promise'
| 'regexp'
| 'set'
| 'string'
| 'symbol'
| 'weakmap'
| 'weakset'
| 'undefined';
// biome-ignore lint/suspicious/noExplicitAny: -
const specialCases = new Map<any, ArgType>([
[null, 'null'],
[undefined, 'undefined'],
]);
/**
* Returns the type of the given argument.
*
* @example
* ```ts
* typeOf(null); // 'null'
* typeOf(undefined); // 'undefined'
* typeOf(NaN); // 'nan'
* typeOf(async function() {}); // 'promise'
* typeOf(123); // 'number'
* typeOf('abc'); // 'string'
* typeOf({}); // 'object'
* typeOf([]); // 'array'
* typeOf(() => {}); // 'function'
* typeOf(new Date()); // 'date'
* typeOf(new Error()); // 'error'
* typeOf(new Map()); // 'map'
* typeOf(new Set()); // 'set'
* typeOf(new WeakMap()); // 'weakmap'
* typeOf(new WeakSet()); // 'weakset'
* typeOf(new RegExp('')); // 'regexp'
* ```
*
* @param arg - The argument whose type is to be determined.
*
* @returns The type of the argument.
*/
export function typeOf(arg: unknown): ArgType {
if (specialCases.has(arg)) return specialCases.get(arg)!;
if (typeof arg === 'number' && Number.isNaN(arg)) return 'nan';
const type = Object.prototype.toString.call(arg).slice(8, -1);
return type === 'AsyncFunction' ? 'promise' : (type.toLowerCase() as ArgType);
}Features
- Isomorphic: Works in both Browser and Node.js.
- Precise Detection: Distinguishes between
'object','array','null', and other specific types. - Consistent Output: Returns lowercase strings for all recognized types.
API
ts
function typeOf(value: unknown): string;Parameters
value: The value whose type needs to be determined.
Returns
- A string representing the type (e.g.,
'string','number','array','object','null','undefined','regexp','date').
Examples
Basic Usage
ts
import { typeOf } from '@vielzeug/toolkit';
typeOf('hello'); // 'string'
typeOf(123); // 'number'
typeOf([]); // 'array'
typeOf({}); // 'object'
typeOf(null); // 'null'
typeOf(undefined); // 'undefined'
typeOf(/abc/); // 'regexp'
typeOf(new Date()); // 'date'Implementation Notes
- Internally uses
Object.prototype.toString.call(value)to extract the internal[[Class]]property. - Performance-optimized for frequent type checking.
- Throws nothing; safe for any input value.