JavaScriptのtypeofには5種類のobject型があるので注意

typeofには5種類のobject型がある

JavaScriptではtypeof演算子を使うとデータ型を調べることができます。

console.log(typeof 123)           // => number
console.log(typeof 'foo')         // => string
console.log(typeof true)          // => boolean
console.log(typeof undefined)     // => undefined
console.log(typeof function() {}) // => function
console.log(typeof Symbol('bar')) // => symbol
console.log(typeof 9876543210n)   // => bigint

しかし、オブジェクト、配列、null、正規表現、new Date()でtypeofを使って型を調べるとすべてobjectになってしまいます。

console.log(typeof { key: 'value' }) // => object
console.log(typeof ['baz'])          // => object
console.log(typeof null)             // => object
console.log(typeof /regex/)          // => object
console.log(typeof new Date())       // => object

getTypeof関数を作成して判定する方法

前述の5種類のobject型は以下のようにgetTypeofのような関数を自作して判別する必要があります。

function getTypeof(value) {
  if (Array.isArray(value)) {
    return 'array'
  } else if (value === null) {
    return 'null'
  } else if (value instanceof RegExp) {
    return 'regexp'
  } else if (value instanceof Date) {
    return 'date'
  } else {
    return typeof value
  }
}

console.log(getTypeof({ key: 'value' })) // => object
console.log(getTypeof(['baz']))          // => array
console.log(getTypeof(null))             // => null
console.log(getTypeof(/regexp/))         // => regexp
console.log(getTypeof(new Date()))       // => date

JavaScriptでは5種類のobject型をわけて判定したいケースが多く、typeofを使うだけではオブジェクトと配列すら同じobjectで返してしまいます。

typeofだけで型を判定するとバグの温床になるので注意が必要です。