typeof能准确判断除null外的6种基本类型:string、number、boolean、undefined、symbol、bigint;null需用===单独判断,因其typeof返回"object"是历史bug。

typeof 运算符能准确判断 JavaScript 中的全部基本数据类型(primitive types),但前提是理解它的规则边界——它对基本类型几乎零误差,唯独 null 是例外。
能准确识别的基本类型有哪些
以下值传入 typeof,返回结果稳定、无歧义,可直接用于逻辑判断:
-
string:任何字符串字面量或 String 原始值,如
typeof "abc"→"string" -
number:包括整数、小数、
Infinity、-Infinity和NaN,如typeof NaN→"number" -
boolean:仅限
true或false,如typeof false→"boolean" -
undefined:变量未赋值、未声明(安全!)、或显式赋为
undefined,如typeof undeclaredVar→"undefined" -
symbol:ES6 引入的唯一原始值,如
typeof Symbol('id')→"symbol" -
bigint:ES10 引入的大整数,需带
n后缀,如typeof 123n→"bigint"
为什么 null 不能算“准确判断”
typeof null 返回 "object",这不是设计意图,而是 V8 引擎早期实现时的历史 bug,被标准保留至今。它本质是空指针值,逻辑上不属于对象,但 typeof 无法反映这一点。所以不能依赖 typeof 区分 null 和普通对象。
若需单独识别 null,必须额外写判断:value === null 或 Object.is(value, null)
函数不是基本类型,但 typeof 对它也“准确”
虽然 function 是引用类型,但 typeof 给出明确返回值 "function",且行为一致可靠:
立即学习“Java免费学习笔记(深入)”;
-
typeof function() {}→"function" -
typeof () => {}→"function" -
typeof class {}→"function"(类本质是语法糖函数)
因此,在区分“是否可调用”时,typeof x === 'function' 是安全有效的判断方式。
实用建议:什么时候该用 typeof
它最适合做轻量、前置、防御性检查:
- 确认变量是否已声明或初始化:
if (typeof config !== 'undefined') { ... } - 区分基本值和对象/数组:
if (typeof data === 'string' || typeof data === 'number') { ... } - 快速筛出函数回调:
if (typeof cb === 'function') cb() - 避免对 undefined 调用方法时报错(比直接
if (x)更安全)
不用于判断数组、日期、正则、null 或自定义对象类型——那些需要 Array.isArray()、instanceof 或 Object.prototype.toString.call() 配合。


















