typeof 能准确识别 string、number、boolean、undefined、symbol、bigint 六种原始类型,但对 null 返回 "object" 属历史 bug,需用 === null 单独判断;对函数返回 "function",可安全用于函数检测,但无法区分数组等对象子类型。

typeof 能准确识别 JavaScript 中的原始类型(primitive types),但有几点关键限制必须清楚——它对 null 返回 "object",对函数返回 "function"(虽属原始类型分类中的特例),其余原始类型(string、number、boolean、undefined、symbol、bigint)则返回对应小写字符串。
能直接靠 typeof 准确判断的原始类型
以下六种原始类型用 typeof 判断是可靠且推荐的:
-
typeof "hello"→"string" -
typeof 42→"number"(包括NaN和Infinity) -
typeof true→"boolean" -
typeof undefined→"undefined"(注意:未声明变量用 typeof 不报错) -
typeof Symbol("id")→"symbol" -
typeof 123n→"bigint"(需确保运行环境支持 BigInt)
typeof 对 null 的误判必须单独处理
null 是原始值,但 typeof null 返回 "object",这是历史遗留 bug。不能依赖它判断是否为 null:
- ❌
typeof null === "object"—— 结果为true,但语义错误 - ✅ 正确方式:
value === null或Object.is(value, null) - 若需统一检测“空值”,可组合:
value === null || typeof value === "undefined"
区分 function 和普通对象要留意返回值
typeof 对函数返回 "function",这在实践中很有用;但要注意它不适用于箭头函数以外的“类函数对象”(如 DOM 元素方法):
-
typeof function(){}→"function" -
typeof () =>{}→"function" -
typeof {}→"object" -
typeof []→"object"(数组不是原始类型,typeof不适用)
所以,typeof 可安全用于判断“是不是函数”,但不能用来区分数组、正则、日期等对象类型——那些需用 Object.prototype.toString.call()。
实际使用建议:优先用 typeof 做轻量预检
在日常开发中,typeof 最适合做快速类型守卫,尤其配合逻辑运算符:
- 检查变量是否已定义且为字符串:
typeof str === "string" && str.length > 0 - 安全读取可能为 undefined 的属性:
typeof obj?.method === "function" && obj.method() - 避免对非数字执行算术:
typeof input === "number" && !isNaN(input)
遇到 null 或需要精确对象子类型时,再叠加其他手段。不复杂但容易忽略。











