typeof 是 JavaScript 中检测数据类型的运算符,返回字符串;能准确识别 undefined、boolean、number、string、symbol、bigint 六种基本类型,但 null 返回 "object" 是历史 bug,函数返回 "function",而所有其他引用类型均返回 "object"。

typeof 是 JavaScript 中用于检测变量或表达式数据类型的运算符,它返回一个表示类型的字符串。对基本数据类型(primitive types)检测准确、简单直接,是日常开发中最常用的类型判断方式之一。
typeof 能识别的 6 种基本类型
JavaScript 有 7 种数据类型,其中 6 种是基本类型(ES2020 新增 bigint),typeof 对它们的返回值如下:
-
undefined→"undefined" -
null→"object"(⚠️这是历史遗留 bug,不是基本类型误判,但需特别注意) -
boolean→"boolean" -
number→"number" -
string→"string" -
symbol→"symbol"(ES6 引入) -
bigint→"bigint"(ES2020 引入)
常见用法与注意事项
使用时可直接写 typeof value 或 typeof(value)(括号非必需,仅用于提高可读性或避免歧义):
- 检测
undefined:typeof undefined === "undefined"✅ - 检测未声明变量:
typeof undeclaredVar === "undefined"✅(不会报错,安全) - 检测
null:typeof null === "object"❌(不是 "null",需单独判断:value === null) - 检测数字字面量或
NaN:typeof NaN === "number"✅(NaN属于 number 类型) - 检测函数:
typeof function(){} === "function"✅(函数在 JS 中是“可调用对象”,但 typeof 单独将其归为"function")
为什么不能靠 typeof 判断对象和数组?
typeof 对所有引用类型(除函数外)都返回 "object":
Java项目代码review工具。分析Git变更+完整调用链路上下文,推断业务需求,进行多维度评分和分类汇总,生成完整PRD文档。包含细粒度Java代码审查清单(Null安全、异常处理、Streams、并发、equals/hashCode、资源管理、API设计、性能、MyBatis/ORM、事务边界、SQL/DD...
立即学习“Java免费学习笔记(深入)”;
typeof [] === "object"typeof {} === "object"typeof new Date() === "object"typeof /regex/ === "object"
因此,要区分数组、日期、正则等,需配合 Array.isArray()、Object.prototype.toString.call() 等方法。
实用小技巧:封装一个基础类型检查工具
可以快速判断是否为某基本类型(排除 null 干扰):
function isType(value, type) {
if (type === 'null') return value === null;
if (type === 'undefined') return typeof value === 'undefined';
return typeof value === type;
}
isType(42, 'number'); // true
isType(null, 'null'); // true
isType([], 'object'); // false(因为 [] 是 object,但这里不等于 'object' 字符串比较,注意逻辑)
更推荐用 Object.prototype.toString.call(value) 做精确类型识别,但 typeof 在判断基本类型时依然高效、轻量、足够可靠。

















