typeof
typeof 运算符返回一个字符串,指示操作数值的类型。
试一试
console.log(typeof 42);
// Expected output: "number"
console.log(typeof "blubber");
// Expected output: "string"
console.log(typeof true);
// Expected output: "boolean"
console.log(typeof undeclaredVariable);
// Expected output: "undefined"
语法
typeof operand
参数
描述
下表总结了 typeof 可能的返回值。有关类型和原始值的更多信息,另请参阅 JavaScript 数据结构页面。
| 类型 | 结果 |
|---|---|
| Undefined | "undefined" |
| Null | "object"(原因) |
| Boolean | "boolean" |
| Number | "number" |
| BigInt | "bigint" |
| String | "string" |
| 符号 | "symbol" |
| 函数(在 ECMA-262 术语中实现 [[Call]];类也是函数) | "function" |
| 任何其他对象 | "object" |
此值列表是详尽的。没有报告符合规范的引擎会产生(或历史上曾产生过)列出之外的值。
示例
基本用法
// Numbers
typeof 37 === "number";
typeof 3.14 === "number";
typeof 42 === "number";
typeof Math.LN2 === "number";
typeof Infinity === "number";
typeof NaN === "number"; // Despite being "Not-A-Number"
typeof Number("1") === "number"; // Number tries to parse things into numbers
typeof Number("shoe") === "number"; // including values that cannot be type coerced to a number
typeof 42n === "bigint";
// Strings
typeof "" === "string";
typeof "bla" === "string";
typeof `template literal` === "string";
typeof "1" === "string"; // note that a number within a string is still typeof string
typeof typeof 1 === "string"; // typeof always returns a string
typeof String(1) === "string"; // String converts anything into a string, safer than toString
// Booleans
typeof true === "boolean";
typeof false === "boolean";
typeof Boolean(1) === "boolean"; // Boolean() will convert values based on if they're truthy or falsy
typeof !!1 === "boolean"; // two calls of the ! (logical NOT) operator are equivalent to Boolean()
// Symbols
typeof Symbol() === "symbol";
typeof Symbol("foo") === "symbol";
typeof Symbol.iterator === "symbol";
// Undefined
typeof undefined === "undefined";
typeof declaredButUndefinedVariable === "undefined";
typeof undeclaredVariable === "undefined";
// Objects
typeof { a: 1 } === "object";
// use Array.isArray or Object.prototype.toString.call
// to differentiate regular objects from arrays
typeof [1, 2, 4] === "object";
typeof new Date() === "object";
typeof /regex/ === "object";
// The following are confusing, dangerous, and wasteful. Avoid them.
typeof new Boolean(true) === "object";
typeof new Number(1) === "object";
typeof new String("abc") === "object";
// Functions
typeof function () {} === "function";
typeof class C {} === "function";
typeof Math.sin === "function";
typeof null
// This stands since the beginning of JavaScript
typeof null === "object";
在 JavaScript 的第一次实现中,JavaScript 值由类型标签和值表示。对象的类型标签是 0。null 被表示为 NULL 指针(在大多数平台上是 0x00)。因此,null 的类型标签是 0,从而导致 typeof 返回值 "object"。(参考)
ECMAScript 曾提出过一个修复方案(通过选择性加入),但被拒绝了。它会导致 typeof null === "null"。
使用 new 运算符
所有使用 new 调用的构造函数都将返回非原始值("object" 或 "function")。大多数返回对象,但一个显著的例外是 Function,它返回一个函数。
const str = new String("String");
const num = new Number(100);
typeof str; // "object"
typeof num; // "object"
const func = new Function();
typeof func; // "function"
语法中需要括号
typeof 运算符的优先级高于加法(+)等二元运算符。因此,需要括号来评估加法结果的类型。
// Parentheses can be used for determining the data type of expressions.
const someData = 99;
typeof someData + " foo"; // "number foo"
typeof (someData + " foo"); // "string"
与未声明和未初始化变量的交互
typeof 通常始终保证为它提供的任何操作数返回一个字符串。即使对于未声明的标识符,typeof 也会返回 "undefined" 而不是抛出错误。
typeof undeclaredVariable; // "undefined"
但是,在同一块中,在声明位置之前对词法声明(let、const 和 class)使用 typeof 将抛出 ReferenceError。块作用域变量从块的开始到初始化处理完成之前都处于暂时性死区,在此期间如果被访问将抛出错误。
typeof newLetVariable; // ReferenceError
typeof newConstVariable; // ReferenceError
typeof newClass; // ReferenceError
let newLetVariable;
const newConstVariable = "hello";
class newClass {}
document.all 的异常行为
所有当前浏览器都暴露了一个非标准的宿主对象 document.all,其类型为 undefined。
typeof document.all === "undefined";
尽管 document.all 也是虚值并宽松等于 undefined,但它不是 undefined。document.all 类型为 "undefined" 的情况在 Web 标准中被归类为对原始 ECMAScript 标准的“蓄意违反”,以实现 Web 兼容性。
获取更具体类型的自定义方法
typeof 非常有用,但它不像可能需要的那样通用。例如,typeof [] 是 "object",typeof new Date()、typeof /abc/ 等也是。
为了在检查类型时获得更大的特异性,我们在此介绍一个自定义的 type(value) 函数,它在很大程度上模仿了 typeof 的行为,但对于非原始值(即对象和函数),它尽可能返回更细粒度的类型名称。
function type(value) {
if (value === null) {
return "null";
}
const baseType = typeof value;
// Primitive types
if (!["object", "function"].includes(baseType)) {
return baseType;
}
// Symbol.toStringTag often specifies the "display name" of the
// object's class. It's used in Object.prototype.toString().
const tag = value[Symbol.toStringTag];
if (typeof tag === "string") {
return tag;
}
// If it's a function whose source code starts with the "class" keyword
if (
baseType === "function" &&
Function.prototype.toString.call(value).startsWith("class")
) {
return "class";
}
// The name of the constructor; for example `Array`, `GeneratorFunction`,
// `Number`, `String`, `Boolean` or `MyCustomClass`
const className = value.constructor.name;
if (typeof className === "string" && className !== "") {
return className;
}
// At this point there's no robust way to get the type of value,
// so we use the base implementation.
return baseType;
}
为了检查可能不存在的变量(否则会抛出 ReferenceError),请使用 typeof nonExistentVar === "undefined",因为这种行为无法通过自定义代码模仿。
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-typeof-operator |
浏览器兼容性
加载中…