util.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // 变量类型判断
  2. export const TypeOfFun = (value: any) => {
  3. if (null === value) {
  4. return 'null';
  5. }
  6. const type = typeof value;
  7. if ('undefined' === type || 'string' === type) {
  8. return type;
  9. }
  10. const typeString = toString.call(value);
  11. switch (typeString) {
  12. case '[object Array]':
  13. return 'array';
  14. case '[object Date]':
  15. return 'date';
  16. case '[object Boolean]':
  17. return 'boolean';
  18. case '[object Number]':
  19. return 'number';
  20. case '[object Function]':
  21. return 'function';
  22. case '[object RegExp]':
  23. return 'regexp';
  24. case '[object Object]':
  25. if (undefined !== value.nodeType) {
  26. if (3 == value.nodeType) {
  27. return /\S/.test(value.nodeValue) ? 'textnode' : 'whitespace';
  28. } else {
  29. return 'element';
  30. }
  31. } else {
  32. return 'object';
  33. }
  34. default:
  35. return 'unknow';
  36. }
  37. };
  38. //
  39. export const objectToString = Object.prototype.toString;
  40. export const toTypeString = (value: unknown): string => objectToString.call(value);
  41. export const toRawType = (value: unknown): string => {
  42. // extract "RawType" from strings like "[object RawType]"
  43. return toTypeString(value).slice(8, -1);
  44. };
  45. export const isArray = Array.isArray;
  46. export const isMap = (val: unknown): val is Map<any, any> => toTypeString(val) === '[object Map]';
  47. export const isSet = (val: unknown): val is Set<any> => toTypeString(val) === '[object Set]';
  48. export const isDate = (val: unknown): val is Date => val instanceof Date;
  49. export const isFunction = (val: unknown): val is Function => typeof val === 'function';
  50. export const isString = (val: unknown): val is string => typeof val === 'string';
  51. export const isSymbol = (val: unknown): val is symbol => typeof val === 'symbol';
  52. export const isObject = (val: unknown): val is Record<any, any> => val !== null && typeof val === 'object';
  53. export const isPromise = <T = any>(val: unknown): val is Promise<T> => {
  54. return isObject(val) && isFunction(val.then) && isFunction(val.catch);
  55. };
  56. export const getPropByPath = (obj: any, keyPath: string) => {
  57. try {
  58. return keyPath.split('.').reduce((prev, curr) => prev[curr], obj);
  59. } catch (error) {
  60. return '';
  61. }
  62. };