紀錄工作經驗、相關知識,解決技術相關問題。

Javascript

JS typeof:判斷資料型別的用法與回傳值對照

JS typeof:判斷資料型別的用法與回傳值對照 特色圖片

JS typeof 是一元運算子,會回傳一個字串,說明運算元的值是哪一種型別。常見的結果有 "number"、"string"、"boolean"、"undefined"、"object"、"function" 等。

console.log(typeof 42);                  // "number"
console.log(typeof "blubber");           // "string"
console.log(typeof true);                // "boolean"
console.log(typeof undeclaredVariable);  // "undefined"

最後一行的 undeclaredVariable 沒有宣告過,typeof 也不會報錯,這是它和一般取值最不同的地方,後面會說明。

語法

typeof operand

typeof 寫在運算元前面,不用加括號,typeof x 與 typeof(x) 都可以。依 MDN 說明,運算元必須是優先順序在 14(前置運算子)以上的運算式,所以遇到加法這類運算式要自己加括號,詳見後面「括號與運算優先順序」一節。

回傳值對照表

typeof 的結果永遠是字串,下表是 MDN 列出的全部可能結果:

值的型別typeof 結果
Undefined"undefined"
Null"object"
Boolean"boolean"
Number"number"
BigInt"bigint"
String"string"
Symbol"symbol"
Function(含 class)"function"
其他任何物件"object"

MDN 指出,這份清單是完整的,符合規範的引擎不會回傳清單以外的值。

console.log(typeof undefined);        // "undefined"
console.log(typeof null);             // "object"
console.log(typeof true);             // "boolean"
console.log(typeof 42);               // "number"
console.log(typeof 42n);              // "bigint"
console.log(typeof "abc");            // "string"
console.log(typeof Symbol("id"));     // "symbol"
console.log(typeof function () {});   // "function"
console.log(typeof {});               // "object"

原始值的結果

數字的結果都是 "number",包含 Infinity、NaN,以及 Number() 轉換失敗得到的 NaN:

console.log(typeof 3.14);              // "number"
console.log(typeof Infinity);          // "number"
console.log(typeof NaN);               // "number"
console.log(typeof Number("shoe"));    // "number"

NaN 的全名是 Not-A-Number,型別卻是 "number",所以 typeof 沒辦法用來判斷 NaN。判斷方式請參考 NaN 與 isNaN()、isFinite() 的語法文。

字串裡的數字還是字串,typeof 本身的結果也是字串:

console.log(typeof "1");              // "string"
console.log(typeof String(1));        // "string"
console.log(typeof typeof 1);         // "string"

布林與 Symbol 的結果如下:

console.log(typeof Boolean(1));       // "boolean"
console.log(typeof !!1);              // "boolean"
console.log(typeof Symbol.iterator);  // "symbol"

Boolean(1) 與 !!1(連續兩次邏輯 NOT)都會把值轉成布林,結果相同。

typeof null 是 "object"

這是 typeof 最常被問到的特例:

console.log(typeof null);   // "object"

依 MDN 說明,這是從 JavaScript 最早的實作就存在的行為。早期的實作用型別標籤加上值來表示資料,物件的型別標籤是 0,而 null 以 NULL 指標表示,在多數平台上就是 0x00,所以 null 的型別標籤也是 0,typeof 就回傳 "object"。

ECMAScript 曾經有人提案修正,讓 typeof null 變成 "null",但提案後來被否決,這個結果因此沿用至今。

所以 typeof value === "object" 的結果不能直接代表「是物件」,要排除 null 要另外檢查:

function isObjectLike(v) {
  return typeof v === "object" && v !== null;
}

console.log(isObjectLike({}));     // true
console.log(isObjectLike([]));     // true
console.log(isObjectLike(null));   // false
console.log(isObjectLike("a"));    // false

null 本身的用法請參考 null 的語法文。

物件、陣列與函式

一般物件、陣列、Date、正規表示式的結果都是 "object":

console.log(typeof { a: 1 });       // "object"
console.log(typeof [1, 2, 4]);      // "object"
console.log(typeof new Date());     // "object"
console.log(typeof /regex/);        // "object"

所以 typeof 分不出陣列和一般物件。MDN 的建議是改用 Array.isArray() 或 Object.prototype.toString.call() 來區分:

console.log(Array.isArray([1, 2, 4]));                 // true
console.log(Array.isArray({ a: 1 }));                  // false
console.log(Object.prototype.toString.call([1, 2, 4])); // "[object Array]"
console.log(Object.prototype.toString.call(new Date())); // "[object Date]"

函式與 class 的結果是 "function",因為 class 本質上也是函式:

class C {}

console.log(typeof function () {});   // "function"
console.log(typeof C);                // "function"
console.log(typeof Math.sin);         // "function"
console.log(typeof (() => {}));       // "function"

要判斷某個值是不是某個類別的實例,可以搭配 instanceof 運算子,它的用法請參考 instanceof 的語法文。

用 new 建立的原始值包裝物件

new String()、new Number()、new Boolean() 建立的是物件,typeof 的結果是 "object",不是 "string" 之類的原始型別:

const str = new String("String");
const num = new Number(100);
const func = new Function();

console.log(typeof str);    // "object"
console.log(typeof num);    // "object"
console.log(typeof func);   // "function"

不加 new 直接呼叫 String()、Number(),是做型別轉換,回傳原始值:

console.log(typeof String("x"));   // "string"
console.log(typeof Number("1"));   // "number"

依 MDN 說明,所有用 new 呼叫的建構函式都會回傳非原始值("object" 或 "function"),其中 Function 是明顯的例外,會回傳函式。MDN 也把 new Boolean(true)、new Number(1)、new String("abc") 這類寫法列為令人困惑、有風險且浪費的寫法,建議避免。

括號與運算優先順序

typeof 的優先順序比加法等二元運算子高,所以它會先作用在左邊的運算元,再做後面的運算。想判斷運算結果的型別,要自己加括號:

const someData = 99;

console.log(typeof someData + " foo");     // "number foo"
console.log(typeof (someData + " foo"));   // "string"

第一行先算 typeof someData 得到 "number",再和 " foo" 相加;第二行先算括號內的 99 + " foo" 得到字串,再取 typeof。

未宣告變數與暫時性死區

typeof 遇到沒有宣告過的識別字,不會丟出錯誤,而是回傳 "undefined":

console.log(typeof undeclaredVariable);   // "undefined"

所以要檢查某個全域變數存不存在,可以寫 typeof name === "undefined"。MDN 指出,這個行為無法用自訂的程式碼模擬,直接取值 name 會丟出 ReferenceError。

但用 let、const、class 宣告的變數,在宣告所在的區塊裡、宣告之前呼叫 typeof,會丟出 ReferenceError,因為這段範圍屬於暫時性死區(temporal dead zone,TDZ):

try {
  typeof newLetVariable;
} catch (e) {
  console.log(e.name);   // "ReferenceError"
}

try {
  typeof newClass;
} catch (e) {
  console.log(e.name);   // "ReferenceError"
}

let newLetVariable;
class newClass {}

const 的情況與 let 相同。範例用 try...catch 接住錯誤,方便看到錯誤名稱;實際寫程式時不應在宣告前使用變數。

常見用法

用 typeof 判斷原始型別,再依型別決定處理方式:

function describe(v) {
  return typeof v === "string" ? "字串" : typeof v === "number" ? "數字" : "其他";
}

console.log(describe("a"));    // "字串"
console.log(describe(1));      // "數字"
console.log(describe(null));   // "其他"

檢查變數是不是 undefined 時,如果變數一定宣告過,直接和 undefined 比較就可以,兩種寫法結果相同:

const maybe = undefined;

console.log(typeof maybe === "undefined");   // true
console.log(maybe === undefined);            // true

undefined 與嚴格相等的細節請參考 undefined 與嚴格相等(===)的語法文。

注意事項

  1. 結果是字串:typeof x === "number" 比較的是字串,拼錯字不會報錯,只會永遠不成立。
  2. typeof null 是 "object":判斷物件時要另外排除 null。
  3. 陣列、Date、正規表示式都是 "object":要區分請用 Array.isArray() 或 instanceof。
  4. NaN 的型別是 "number":不能用 typeof 判斷 NaN。
  5. 宣告前使用 let、const、class:即使是 typeof 也會丟出 ReferenceError。
  6. document.all:MDN 說明所有目前的瀏覽器都提供這個非標準物件,它的 typeof 結果是 "undefined",這是規範為了網頁相容性而列的「刻意違反」例外,一般文章不會遇到。

支援版本

依 MDN 瀏覽器相容性資料(browser-compat-data 8.1.10,查詢日期 2026-11-24):typeof 從 Chrome 1、Edge 12、Firefox 1、Safari 1 開始支援,Node.js 從 0.10.0 開始,Deno 從 1.0 開始,Internet Explorer 從 3 開始。

補充說明:範例在 Node.js 執行。MDN 的範例是原始值的各種結果、typeof null、new 建立的物件、括號與優先順序、未宣告變數與暫時性死區;isObjectLike()、describe() 與 Array.isArray() 的範例是依 MDN 的說明另外示範的。

參考資料與延伸閱讀

發佈留言