typeof 能准确识别 number、string、boolean、undefined、symbol、bigint 六种基本类型,但对 null 错误返回 "object";无法区分数组、对象等引用类型,仅函数返回 "function"。

直接用 typeof 就能检测基本数据类型,但要注意它对 null 的返回是错的——会返回 "object",不是 "null"。
哪些基本类型能被 typeof 准确识别
typeof 对以下 6 种原始类型(primitive)返回结果准确且稳定:
-
number:包括整数、小数、
NaN、Infinity,都返回"number" -
string:普通字符串、空字符串、模板字面量,都返回
"string" -
boolean:
true和false都返回"boolean" -
undefined:未声明变量或显式赋值为
undefined,返回"undefined" -
symbol:任何 Symbol 值(如
Symbol('a')),返回"symbol" -
bigint:ES2020 新增,带
n后缀的整数字面量(如123n),返回"bigint"
null 是唯一“失准”的基本类型
typeof null 返回 "object",这是 JavaScript 诞生时的历史 bug,一直保留至今。所以不能单靠 typeof 判断 null:
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
- 错误写法:
typeof x === "object" && x !== null—— 这样漏掉了null本身 - 正确做法:单独加判断,
x === null或Object.is(x, null)
别误把引用类型当基本类型测
typeof 不适合检测数组、对象、日期等引用类型,因为它们统一返回 "object"(除了函数):
-
typeof []→"object" -
typeof {}→"object" -
typeof new Date()→"object" -
typeof /abc/→"object" - 但
typeof function() {}→"function"(这是唯一例外)
实用检测组合建议
日常判断基本类型,推荐这样写:
- 检查是否为字符串:
typeof x === "string" - 检查是否为数值:
typeof x === "number" && !isNaN(x)(排除NaN) - 检查是否为布尔值:
typeof x === "boolean" - 检查是否为
null:x === null - 检查是否为
undefined:typeof x === "undefined"(比x === undefined更安全,不报错)
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










