Back to Snippets
CODE

Precise Data Type Detection

Description

Replaces typeof to solve inaccurate type checking issues (e.g., typeof null === 'object'), returns lowercase precise type string

Code

/**
 * Precise data type detection
 * @param value Value to be detected
 * @returns Type string (string/number/array/object/null/date etc.)
 */
function getType(value: unknown): string {
  return Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
}

// Usage Example
console.log(getType('hello')); // 'string'
console.log(getType(null)); // 'null'
console.log(getType([])); // 'array'
console.log(getType(new Date())); // 'date'

Usage

Ideal for scenarios requiring precise type differentiation, such as form validation or type checking before data processing

Tags

Type CheckingUtility FunctionBasic