typeof 返回值對照表
| 值類型 | typeof 結果 | 示例 |
| Undefined | "undefined" | typeof undefined |
| Null | "object" ⚠️ | typeof null |
| Boolean | "boolean" | typeof true |
| Number | "number" | typeof 42 / typeof NaN / typeof Infinity |
| BigInt (ES2020) | "bigint" | typeof 10n |
| String | "string" | typeof "hello" / typeof `template` |
| Symbol (ES6) | "symbol" | typeof Symbol() |
| Function | "function" | typeof function(){} / typeof class C{} |
| Object/Array/Date/RegExp/Map/Set/Promise... | "object" | typeof {} / typeof [] / typeof new Date() |
兩種寫法等價
typeof variable; // 作為操作符
typeof(variable); // 作為函數調用形式 (實際仍是操作符)
// 兩者結果完全一致,括號僅為分組
經典陷阱:null 是 object
typeof null === 'object'; // true — JavaScript 設計失誤 (第一版本類型標籤 0 表示對象,null 全零被誤判)
// 正確判斷 null
var isNull = (val === null);
// 或組合
var isNull = (val == null); // 同時檢測 null/undefined (鬆散相等)
無法區分的對象子類型
typeof [] === 'object'; // true
typeof {} === 'object'; // true
typeof new Date() === 'object'; // true
typeof /re/ === 'object'; // true
typeof new Map() === 'object'; // true
typeof null === 'object'; // true (!)
// 都返回 "object",需用其他方法區分
進階精準判斷方案
1. Array.isArray() (ES5) - 判斷數組首選
Array.isArray([]); // true
Array.isArray({}); // false
Array.isArray(arguments); // false (類數組)
Array.isArray(new Array()); // true
2. Object.prototype.toString.call() - 萬能精準判斷
function getType(val) {
return Object.prototype.toString.call(val).slice(8, -1).toLowerCase();
}
getType([]); // "array"
getType({}); // "object"
getType(null); // "null"
getType(undefined); // "undefined"
getType(/re/); // "regexp"
getType(new Date()); // "date"
getType(Promise.resolve()); // "promise"
getType(new Map()); // "map"
getType(function(){}); // "function" (注意: typeof 也能判函數)
3. instanceof - 判斷構造函數原型鏈
[] instanceof Array; // true
[] instanceof Object; // true
new Date() instanceof Date; // true
function(){} instanceof Function; // true
// ⚠️ 跨 iframe/frame 失效
// ⚠️ 原型被篡改失效
4. 鴨子類型檢測 - 檢測能力而非類型
// 可迭代
function isIterable(obj) { return obj != null && typeof obj[Symbol.iterator] === 'function'; }
// 類數組
function isArrayLike(obj) { return obj != null && typeof obj.length === 'number' && obj.length >= 0; }
// Thenable (Promise-like)
function isThenable(obj) { return obj && typeof obj.then === 'function'; }
實戰封裝:通用類型判斷工具庫
const Type = {
// 基礎類型
isUndefined: v => v === undefined,
isNull: v => v === null,
isBoolean: v => typeof v === 'boolean',
isNumber: v => typeof v === 'number' && !isNaN(v),
isNaN: v => Number.isNaN(v), // ES6 推薦
isString: v => typeof v === 'string',
isSymbol: v => typeof v === 'symbol',
isBigInt: v => typeof v === 'bigint',
isFunction: v => typeof v === 'function',
// 對象類型
isObject: v => v !== null && typeof v === 'object',
isArray: Array.isArray,
isPlainObject: v => Object.prototype.toString.call(v) === '[object Object]',
isDate: v => Object.prototype.toString.call(v) === '[object Date]',
isRegExp: v => Object.prototype.toString.call(v) === '[object RegExp]',
isError: v => Object.prototype.toString.call(v) === '[object Error]',
isPromise: v => Object.prototype.toString.call(v) === '[object Promise]',
isMap: v => Object.prototype.toString.call(v) === '[object Map]',
isSet: v => Object.prototype.toString.call(v) === '[object Set]',
// 空值
isEmpty: v => {
if (v == null) return true;
if (typeof v === 'string' || Array.isArray(v)) return v.length === 0;
if (Type.isObject(v)) return Object.keys(v).length === 0;
return false;
},
// 統一入口
getType: v => v === null ? 'null' : typeof v === 'object' ? Object.prototype.toString.call(v).slice(8, -1).toLowerCase() : typeof v
};
// 使用
Type.getType([]); // "array"
Type.isArray([1,2]); // true
Type.isEmpty({}); // true
Type.isThenable(Promise.resolve()); // true (自行添加)
TypeScript 類型守衛
// 用戶定義類型守衛
function isString(val: any): val is string {
return typeof val === 'string';
}
function isArray(val: any): val is any[] {
return Array.isArray(val);
}
function process(val: string | string[]) {
if (isString(val)) { console.log(val.toUpperCase()); }
else if (isArray(val)) { console.log(val.join(', ')); }
}
總結建議
- ✅ 原始類型 + function:用
typeof
- ✅ 數組:用
Array.isArray()
- ✅ null:用
val === null
- ✅ 所有內置對象精準區分:用
Object.prototype.toString.call()
- ✅ 自定義類實例:同一 Realm 用
instanceof,跨 Realm 用 toString
- ✅ 能力檢測優於類型檢測:如
if (obj.then) 代替 isPromise