type-check.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. const objectToString = Object.prototype.toString;
  2. const toTypeString = (value: any) => objectToString.call(value);
  3. export const { isArray } = Array;
  4. export const isMap = (val: any) => toTypeString(val) === '[object Map]';
  5. export const isSet = (val: any) => toTypeString(val) === '[object Set]';
  6. export const isDate = (val: any) => val instanceof Date;
  7. export const isFunction = (val: any) => typeof val === 'function';
  8. export const isString = (val: any) => typeof val === 'string';
  9. export const isSymbol = (val: any) => typeof val === 'symbol';
  10. export const isObject = (val: any) => val !== null && typeof val === 'object';
  11. export const isPromise = (val: any) =>
  12. isObject(val) && isFunction(val.then) && isFunction(val.catch);
  13. // Determine whether it is url
  14. export const isUrl = (url: string) => {
  15. return /^(https?:\/\/(([a-zA-Z0-9]+-?)+[a-zA-Z0-9]+\.)+[a-zA-Z]+)(:\d+)?(\/.*)?(\?.*)?(#.*)?$/.test(
  16. url,
  17. );
  18. };
  19. // Determine if it is a JSON string
  20. export const isJSON = (str: string) => {
  21. // eslint-disable-next-line no-useless-escape
  22. if (typeof str === 'string') {
  23. try {
  24. const data = JSON.parse(str);
  25. if (data) {
  26. return true;
  27. }
  28. return false;
  29. } catch (error: any) {
  30. return false;
  31. }
  32. }
  33. return false;
  34. };
  35. // Determine if it is a JSON string
  36. export const JSONToObject = (str: string) => {
  37. if (!str || !isJSON(str)) {
  38. return str;
  39. }
  40. return JSON.parse(str);
  41. };