Skip to content

js 类型判定

更新于: at 07:46
  1. 方法一
/**
 * JavaScript 类型映射表
 */
interface JavaScriptType {
  number: number;
  boolean: boolean;
  string: string;
  undefined: undefined;
  null: null;
  symbol: symbol;
  bigint: bigint;
  object: object;
  function: Function;
  array: Array<any>;
  date: Date;
  regexp: RegExp;
  promise: Promise<any>;
  formdata: FormData;
}

/** JavaScript 类型 */
type JavaScriptTypes = keyof JavaScriptType;

/**
 * 检测类型
 * @param target 检测的目标
 */
const checkType = (target: any): JavaScriptTypes => {
  const value = Object.prototype.toString.call(target);
  const result = (value.match(/\[object (\S*)\]/) as RegExpMatchArray)[1];
  return result.toLocaleLowerCase() as JavaScriptTypes;
}

/**
 * 判断任意值的类型,作用与 checkType 一致,外加一个辅助功能:当函数返回值为 true 时,可以传入泛型来确定 target 的类型(类型收窄)
 * @param target 判断目标
 * @param type 判断的类型
 * - 当要判断的类型为 object 时,需要传一个泛型去确定它的类型,因为在 ts 中 object 是一个特殊类型无法确定
 * @example
 * ```ts
 * type User = {
 *   id: number
 *   name: string
 * }
 * 
 * const setData = (params: string | User | Array<User>) => {
 *   if (isType<User>(params, 'object')) {
 *     params.name = 'xxx';
 *   }
 *   if (isType(params, 'array')) {
 *     params.push({ id: 1, name: 'add' });
 *   }
 *   // ...do some
 * }
 * ```
 */
const isType = <T>(target: any, type: T extends 'object' ? T : JavaScriptTypes): target is T extends JavaScriptTypes ? JavaScriptType[T] : T => {
  return checkType(target) === type;
}
  1. 方法二
const isNull = (p: any): p is null => {
  return p === null;
};
const isNumber = (p: any): p is number => {
  return typeof p === 'number';
};
const isArray = (p: any): p is [] => {
  return Array.isArray(p);
};
const isFunction = (p: any): p is Function => {
  return p instanceof Function;
};
const isObject = (p: any): p is Object => {
  return Object.prototype.toString.call(p) === '[object Object]';
};