Lodash provides rich type checking methods. Here is a detailed answer about Lodash type checking:
Lodash Type Checking Methods Overview
Lodash provides many type checking methods to determine the type of values. These methods are more accurate and reliable than native typeof and instanceof.
1. Basic Type Checking
_.isBoolean(value)
Checks if value is a boolean type.
javascript_.isBoolean(false); // => true _.isBoolean(null); // => false // Real application: Validate boolean parameters function processFlag(flag) { if (!_.isBoolean(flag)) { throw new Error('Flag must be a boolean'); } return flag ? 'enabled' : 'disabled'; }
_.isNumber(value)
Checks if value is a number.
javascript_.isNumber(3); // => true _.isNumber(Number.MIN_VALUE); // => true _.isNumber(Infinity); // => true _.isNumber('3'); // => false // Real application: Validate number input function calculateDiscount(price, discount) { if (!_.isNumber(price) || !_.isNumber(discount)) { throw new Error('Price and discount must be numbers'); } return price * (1 - discount); }
_.isString(value)
Checks if value is a string.
javascript_.isString('abc'); // => true _.isString(1); // => false // Real application: Validate string input function sanitizeInput(input) { if (!_.isString(input)) { return String(input); } return _.trim(input); }
_.isFunction(value)
Checks if value is a function.
javascript_.isFunction(_); // => true _.isFunction(/abc/); // => false // Real application: Validate callback function function executeCallback(callback) { if (!_.isFunction(callback)) { console.warn('Callback is not a function'); return; } callback(); }
2. Object Type Checking
_.isObject(value)
Checks if value is an object type (including arrays, functions, objects, etc.).
javascript_.isObject({}); // => true _.isObject([1, 2, 3]); // => true _.isObject(_.noop); // => true _.isObject(null); // => false // Real application: Check if value is object type function processValue(value) { if (_.isObject(value)) { return _.cloneDeep(value); } return value; }
_.isPlainObject(value)
Checks if value is a plain object (object created through Object constructor).
javascriptfunction Foo() { this.a = 1; } _.isPlainObject(new Foo()); // => false _.isPlainObject([1, 2, 3]); // => false _.isPlainObject({ 'x': 0, 'y': 0 }); // => true _.isPlainObject(Object.create(null)); // => true // Real application: Validate configuration object function validateConfig(config) { if (!_.isPlainObject(config)) { throw new Error('Config must be a plain object'); } return config; }
_.isObjectLike(value)
Checks if value is object-like (not null and typeof is 'object').
javascript_.isObjectLike({}); // => true _.isObjectLike([1, 2, 3]); // => true _.isObjectLike(_.noop); // => false _.isObjectLike(null); // => false
3. Array Type Checking
_.isArray(value)
Checks if value is an array.
javascript_.isArray([1, 2, 3]); // => true _.isArray(document.body.children); // => false _.isArray('abc'); // => false _.isArray(_.noop); // => false // Real application: Validate array input function processItems(items) { if (!_.isArray(items)) { items = [items]; } return _.map(items, item => transform(item)); }
_.isArrayLike(value)
Checks if value is array-like (has length property and is a non-negative integer).
javascript_.isArrayLike([1, 2, 3]); // => true _.isArrayLike(document.body.children); // => true _.isArrayLike('abc'); // => true _.isArrayLike(_.noop); // => false
4. Empty Value Checking
_.isEmpty(value)
Checks if value is empty.
javascript_.isEmpty(null); // => true _.isEmpty(true); // => true _.isEmpty(1); // => true _.isEmpty([1, 2, 3]); // => false _.isEmpty({ 'a': 1 }); // => false _.isEmpty(''); // => true _.isEmpty(' '); // => false // Real application: Validate required fields function validateRequired(value, fieldName) { if (_.isEmpty(value)) { throw new Error(`${fieldName} is required`); } return value; }
_.isNil(value)
Checks if value is null or undefined.
javascript_.isNil(null); // => true _.isNil(void 0); // => true _.isNil(NaN); // => false // Real application: Safe property access function safeGet(obj, path) { const value = _.get(obj, path); return _.isNil(value) ? null : value; }
5. Number Type Checking
_.isInteger(value)
Checks if value is an integer.
javascript_.isInteger(3); // => true _.isInteger(Number.MIN_VALUE); // => false _.isInteger(Infinity); // => false _.isInteger('3'); // => false // Real application: Validate integer input function validateCount(count) { if (!_.isInteger(count) || count < 0) { throw new Error('Count must be a positive integer'); } return count; }
_.isFinite(value)
Checks if value is a finite number.
javascript_.isFinite(3); // => true _.isFinite(Number.MIN_VALUE); // => true _.isFinite(Infinity); // => false _.isFinite('3'); // => false // Real application: Validate finite number function calculate(value) { if (!_.isFinite(value)) { throw new Error('Value must be a finite number'); } return Math.sqrt(value); }
_.isNaN(value)
Checks if value is NaN (more accurate than native isNaN).
javascript_.isNaN(NaN); // => true _.isNaN(new Number(NaN)); // => true isNaN(undefined); // => true _.isNaN(undefined); // => false // Real application: Validate number calculation result function divide(a, b) { const result = a / b; if (_.isNaN(result)) { throw new Error('Invalid calculation result'); } return result; }
6. Date and RegExp Checking
_.isDate(value)
Checks if value is a Date object.
javascript_.isDate(new Date()); // => true _.isDate('Mon April 23 2012'); // => false // Real application: Validate date input function formatDate(date) { if (!_.isDate(date)) { date = new Date(date); } return date.toISOString(); }
_.isRegExp(value)
Checks if value is a regular expression.
javascript_.isRegExp(/abc/); // => true _.isRegExp('/abc/'); // => false // Real application: Validate regular expression function compilePattern(pattern) { if (_.isRegExp(pattern)) { return pattern; } return new RegExp(pattern); }
7. Element Checking
_.isElement(value)
Checks if value is a DOM element.
javascript_.isElement(document.body); // => true _.isElement('<body>'); // => false // Real application: Validate DOM element function attachListener(element, event, handler) { if (!_.isElement(element)) { throw new Error('Element must be a DOM element'); } element.addEventListener(event, handler); }
_.isArguments(value)
Checks if value is an arguments object.
javascript_.isArguments(function() { return arguments; }()); // => true _.isArguments([1, 2, 3]); // => false
8. Other Type Checking
_.isError(value)
Checks if value is an Error object.
javascript_.isError(new Error()); // => true _.isError(Error); // => false // Real application: Error handling function handleError(error) { if (_.isError(error)) { console.error(error.message); return; } console.error('Unknown error:', error); }
_.isSymbol(value)
Checks if value is a Symbol.
javascript_.isSymbol(Symbol.iterator); // => true _.isSymbol('abc'); // => false // Real application: Check Symbol property function hasSymbolProperty(obj, sym) { return _.isSymbol(sym) && sym in obj; }
_.isTypedArray(value)
Checks if value is a typed array.
javascript_.isTypedArray(new Uint8Array()); // => true _.isTypedArray([]); // => false // Real application: Process binary data function processData(data) { if (_.isTypedArray(data)) { return processBinaryData(data); } return processRegularData(data); }
_.isWeakMap(value)
Checks if value is a WeakMap.
javascript_.isWeakMap(new WeakMap()); // => true _.isWeakMap(new Map()); // => false
_.isWeakSet(value)
Checks if value is a WeakSet.
javascript_.isWeakSet(new WeakSet()); // => true _.isWeakSet(new Set()); // => false
_.isMap(value)
Checks if value is a Map.
javascript_.isMap(new Map()); // => true _.isMap(new WeakMap()); // => false
_.isSet(value)
Checks if value is a Set.
javascript_.isSet(new Set()); // => true _.isSet(new WeakSet()); // => false
Real-World Application Examples
Type Validator
javascriptclass TypeValidator { static validate(value, type) { const validators = { 'string': _.isString, 'number': _.isNumber, 'boolean': _.isBoolean, 'array': _.isArray, 'object': _.isPlainObject, 'function': _.isFunction, 'date': _.isDate, 'regexp': _.isRegExp }; const validator = validators[type]; if (!validator) { throw new Error(`Unknown type: ${type}`); } return validator(value); } static validateSchema(data, schema) { const errors = []; _.forOwn(schema, (type, field) => { const value = data[field]; if (!_.isNil(value) && !this.validate(value, type)) { errors.push(`${field} must be ${type}`); } }); return { valid: errors.length === 0, errors }; } } const schema = { name: 'string', age: 'number', active: 'boolean', tags: 'array' }; const data = { name: 'John', age: 30, active: true, tags: ['developer', 'javascript'] }; const result = TypeValidator.validateSchema(data, schema); // => { valid: true, errors: [] }
Safe Data Access
javascriptclass SafeAccessor { static get(obj, path, defaultValue = null) { const value = _.get(obj, path); return _.isNil(value) ? defaultValue : value; } static getNumber(obj, path, defaultValue = 0) { const value = _.get(obj, path); return _.isNumber(value) ? value : defaultValue; } static getString(obj, path, defaultValue = '') { const value = _.get(obj, path); return _.isString(value) ? value : defaultValue; } static getArray(obj, path, defaultValue = []) { const value = _.get(obj, path); return _.isArray(value) ? value : defaultValue; } static getObject(obj, path, defaultValue = {}) { const value = _.get(obj, path); return _.isPlainObject(value) ? value : defaultValue; } } const data = { user: { name: 'John', age: 30, tags: ['developer'] } }; console.log(SafeAccessor.getString(data, 'user.name')); // => 'John' console.log(SafeAccessor.getNumber(data, 'user.age')); // => 30 console.log(SafeAccessor.getArray(data, 'user.tags')); // => ['developer'] console.log(SafeAccessor.getObject(data, 'user.profile')); // => {}
Type Converter
javascriptclass TypeConverter { static toString(value) { if (_.isString(value)) return value; if (_.isNil(value)) return ''; if (_.isDate(value)) return value.toISOString(); return String(value); } static toNumber(value) { if (_.isNumber(value)) return value; if (_.isString(value)) { const num = Number(value); return _.isNaN(num) ? 0 : num; } if (_.isBoolean(value)) return value ? 1 : 0; return 0; } static toArray(value) { if (_.isArray(value)) return value; if (_.isNil(value)) return []; if (_.isString(value)) return _.split(value, ''); return [value]; } static toObject(value) { if (_.isPlainObject(value)) return value; if (_.isArray(value)) return _.fromPairs(value); return {}; } } console.log(TypeConverter.toString(123)); // => '123' console.log(TypeConverter.toNumber('123')); // => 123 console.log(TypeConverter.toArray('abc')); // => ['a', 'b', 'c'] console.log(TypeConverter.toObject([['a', 1], ['b', 2]])); // => { a: 1, b: 2 }
Summary
Lodash provides rich type checking methods, including:
- Basic Type Checking:
_.isBoolean,_.isNumber,_.isString,_.isFunction - Object Type Checking:
_.isObject,_.isPlainObject,_.isObjectLike - Array Type Checking:
_.isArray,_.isArrayLike - Empty Value Checking:
_.isEmpty,_.isNil - Number Type Checking:
_.isInteger,_.isFinite,_.isNaN - Date and RegExp Checking:
_.isDate,_.isRegExp - Element Checking:
_.isElement,_.isArguments - Other Type Checking:
_.isError,_.isSymbol,_.isTypedArray, etc.
These type checking methods are more accurate and reliable than native typeof and instanceof. In actual development, it's recommended to use these methods for type validation to improve code robustness and maintainability.