const class2type: any = {}; const { toString } = class2type; // 设定数据类型的映射表 const types = ['Boolean', 'Number', 'String', 'Function', 'Array', 'Date', 'RegExp', 'Object', 'Error', 'Symbol']; types.forEach((type) => { class2type[`[object ${type}]`] = type.toLowerCase(); }); const typeOf = (source: unknown): string => { if (source === null || source === undefined) { // 传递的值是null或者undefined,就返回对应的字符串 return `${source}`; } // 基本数据类型都采用typeof检测 return typeof source === 'object' || typeof source === 'function' ? class2type[toString.call(source)] || 'object' : typeof source; }; /** * 是否是对象 * @param source */ const isObject = (source: unknown): boolean => typeOf(source) === 'object'; /** * 是否是boolean * @param source */ const isBoolean = (source: unknown): boolean => typeOf(source) === 'boolean'; /** * 是否是字符串 * @param source */ const isString = (source: unknown): boolean => typeOf(source) === 'string'; /** * 是否是对象 * @param source */ const isNumber = (source: unknown): boolean => typeOf(source) === 'number'; /** * 是否是正则表达式 * @param source */ const isRegExp = (source: unknown): boolean => typeOf(source) === 'regexp'; /** * 是否是方法 * @param source */ const isFunction = (source: unknown): boolean => typeOf(source) === 'function'; /** * 是否是undefined * @param source */ const isUndefined = (source: unknown): boolean => typeOf(source) === 'undefined'; /** * 是否是数组 * @param source */ const isArray = (source: unknown): boolean => typeOf(source) === 'array'; /** * 是否为空 * @param source */ const isEmpty = (source: unknown): boolean => { if (source === undefined || source === null) return true; if (isString(source) || isArray(source)) return (source as string|Array).length === 0; if (isObject(source)) return JSON.stringify(source) === '{}'; return (source as any).toString().length === 0; }; export { isObject, isBoolean, isString, isNumber, isRegExp, isFunction, isUndefined, isArray, isEmpty, typeOf, };