You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取对象中声明为String/Number/Date函数类型字段的实际类型?

如何判断构造函数对应的实际类型

这个问题我碰到过好多次——当你拿到String、Number这类原生构造函数时,typeof只会返回'function',完全没法直接知道它们对应的原始类型;碰到[String]这种数组形式的构造器时就更头疼了。下面给你几个实用的解决方案:

方案一:构造函数映射表(简单直接)

最稳妥的方式是给已知的原生构造函数做一个映射表,直接返回对应的类型字符串,同时处理数组的情况:

// 先定义原生构造函数到类型的映射
const constructorToType = {
  [String]: 'string',
  [Number]: 'number',
  [Date]: 'date'
};

function getActualType(target) {
  // 先判断是不是数组类型的构造器(比如[String])
  if (Array.isArray(target)) {
    const innerType = constructorToType[target[0]];
    return innerType ? `array of ${innerType}` : 'unknown array type';
  }
  // 处理单个构造函数
  return constructorToType[target] || 'unknown type';
}

// 测试你的示例
const obj = { key: String, key1: Number, key2: [String] };
console.log(getActualType(obj.key));   // 输出: 'string'
console.log(getActualType(obj.key1));  // 输出: 'number'
console.log(getActualType(obj.key2));  // 输出: 'array of string'

这个方法的好处是性能高、逻辑清晰,如果后面需要支持更多原生构造函数(比如Boolean),直接往映射表里加就行。

方案二:通过实例推导(动态适配)

如果需要支持一些不确定的构造函数,可以通过创建实例来推导类型,同时处理Date这类特殊情况(因为typeof new Date()会返回'object',不是我们想要的'date'):

function getActualType(target) {
  // 处理数组构造器
  if (Array.isArray(target)) {
    const innerConstructor = target[0];
    try {
      // 创建实例来判断类型
      const instance = new innerConstructor();
      let innerType = typeof instance;
      // 特殊处理Date类型
      if (innerConstructor === Date) {
        innerType = 'date';
      }
      return `array of ${innerType}`;
    } catch (err) {
      // 碰到需要参数才能实例化的构造函数(比如Error)时返回未知
      return 'unknown array type';
    }
  }

  // 处理单个构造函数
  if (typeof target === 'function') {
    try {
      const instance = new target();
      let type = typeof instance;
      // 区分Date和普通对象
      if (target === Date) {
        type = 'date';
      }
      return type;
    } catch (err) {
      return 'unknown type';
    }
  }

  // 不是函数的话直接返回typeof结果
  return typeof target;
}

// 测试扩展场景
console.log(getActualType(Date));      // 输出: 'date'
console.log(getActualType([Date]));    // 输出: 'array of date'
console.log(getActualType(Boolean));   // 输出: 'boolean'

这个方法的优势是不需要手动维护映射表,能自动适配大部分构造函数,但要注意有些构造函数必须传入参数才能实例化(比如new Error()可以,但复杂的自定义构造函数可能会报错),所以一定要加try-catch捕获异常。

额外补充:自定义构造函数的处理

如果你的场景里有自定义构造函数,比如function User() {},可以通过构造函数的name属性来返回更有意义的类型:

function getActualType(target) {
  // ... 前面的数组和原生类型处理逻辑
  
  if (typeof target === 'function') {
    // 优先返回自定义构造函数的名称(转小写或者直接用)
    return target.name.toLowerCase() || 'custom object';
  }
  
  return typeof target;
}

// 测试
function User() {}
console.log(getActualType(User)); // 输出: 'user'

内容的提问来源于stack exchange,提问作者muthu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 14:27:38