自分用メモ
型 | 値 | typeof | toString.call |
---|---|---|---|
string | "", "abc", 'a', String(1) | string | [object String] |
String | new String("") | object | [object String] |
number | 0, NaN, Infinity, Number('1') | number | [object Number] |
Number | new Number(0) | object | [object Number] |
bigint | 1n, BigInt(1) | bigint | [object BigInt] |
Bigint | Object(1n) | object | [object BigInt] |
boolean | true, Boolean(0) | boolean | [object Boolean] |
Boolean | new Boolean(true) | object | [object Boolean] |
symbol | Symbol(1) | symbol | [object Symbol] |
Symbol | Object(Symbol(1)) | object | [object Symbol] |
null | null | object | [object Null] |
undefined | undefined | undefined | [object Undefined] |
array | [] | object | [object Array] |
object | {} | object | [object Object] |
function | () => {} | function | [object Function] |
Map | new Map() | object | [object Map] |
Set | new Set() | object | [object Set] |
Date | new Date() | object | [object Date] |
Error | new Error() | object | [object Error] |
開発者ツールのコンソールで試せるコード
console.log('string: ', typeof 'a', Object.prototype.toString.call('a'))
console.log('String: ', typeof new String(""), Object.prototype.toString.call(new String("")))
console.log('number: ', typeof 0, Object.prototype.toString.call(0))
console.log('Number: ', typeof new Number(0), Object.prototype.toString.call(new Number(0)))
console.log('boolean: ', typeof true, Object.prototype.toString.call(true))
console.log('Boolean: ', typeof new Boolean(true), Object.prototype.toString.call(new Boolean(true)))
console.log('bigint: ', typeof 1n, Object.prototype.toString.call(1n))
console.log('BigInt: ', typeof Object(1n), Object.prototype.toString.call(Object(1n)))
console.log('symbol: ', typeof Symbol(1), Object.prototype.toString.call(Symbol(1)))
console.log('Symbol: ', typeof Object(Symbol(1)), Object.prototype.toString.call(Object(Symbol(1))))
console.log('null: ', typeof null, Object.prototype.toString.call(null))
console.log('undefined: ', typeof undefined, Object.prototype.toString.call(undefined))
console.log('array: ', typeof [], Object.prototype.toString.call([]))
console.log('object: ', typeof {}, Object.prototype.toString.call({}))
console.log('function: ', typeof (() => {}), Object.prototype.toString.call((() => {})))
console.log('Map: ', typeof new Map(), Object.prototype.toString.call(new Map()))
console.log('Set: ', typeof new Set(), Object.prototype.toString.call(new Set()))
console.log('Date: ', typeof new Date(), Object.prototype.toString.call(new Date()))
console.log('Error: ', typeof new Error(), Object.prototype.toString.call(new Error()))
toString.call
を使うなら、以下のような感じで判別に使える
const getType = (a: any): string =>
Object.prototype.toString.call(a).replace('[object ', '').replace(']', '')
if (getType('hoge') === 'String') console.log('string')
// -> string
参考