← 中文资源

简体中文版本

typeof 与 Array.isArray 组合类型检查

typeof 把 null 和数组都报告成 object:先挡空值,再用 Array.isArray 区分数组与普通对象,两个检查组合才构成可靠的白名单守卫。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

null       typeof = null       Array.isArray = false
undefined  typeof = undefined  Array.isArray = false
number     typeof = number     Array.isArray = false
NaN        typeof = number     Array.isArray = false
string     typeof = string     Array.isArray = false
boolean    typeof = boolean    Array.isArray = false
array      typeof = object     Array.isArray = true
object     typeof = object     Array.isArray = false
function   typeof = function   Array.isArray = false
bigint     typeof = bigint     Array.isArray = false
typeof null is object - the guard above rejects it first
isPlainObject passes for: object

实现说明

typeof 与 Array.isArray 组合类型检查可以归结为函数 isPlainObject。 这个示例中仅有的重复出现在 for (const [label, value] of samples) 里。

使用要点

  • 跑完文件,输出里会留下标记——typeof null is、isPlainObject passes for:。

常见问题

运行之前需要装什么吗?

不需要——用到的每个 API 都随语言运行时自带,无需安装。 文件在加载时定义 isPlainObject。

主要签名是 function isPlainObject(value)

核心语句

const passed = samples.filter(([, v]) => isPlainObject(v)).map(([label]) => label);
return typeof value === 'object' && value !== null && !Array.isArray(value);

代码示例

// Runtime type checks for values that come back from JSON payloads
const samples = [
  ['null', null],
  ['undefined', undefined],
  ['number', 42],
  ['NaN', NaN],
  ['string', 'text'],
  ['boolean', true],
  ['array', []],
  ['object', {}],
  ['function', () => {}],
  ['bigint', 10n],
];

for (const [label, value] of samples) {
  const kind = value === null ? 'null' : typeof value;
  console.log(label.padEnd(10), 'typeof =', kind.padEnd(10), 'Array.isArray =', Array.isArray(value));
}

// typeof null 报告 'object' 是历史遗留:先挡空值,再用 Array.isArray 区分数组
function isPlainObject(value) {
  return typeof value === 'object' && value !== null && !Array.isArray(value);
}

console.log('typeof null is', typeof null, '- the guard above rejects it first');
const passed = samples.filter(([, v]) => isPlainObject(v)).map(([label]) => label);
console.log('isPlainObject passes for:', passed.join(', '));