Skip to content
Moa Torres edited this page Aug 1, 2021 · 12 revisions

Node.js Object TypeTags

String representations of object in Node.js

This package contains a list of default string representations of objects in Node.js, as returned from Object.prototype.toString.call(value)see the full list here.

📦 typetags

NPM

npm install typetags

Yarn

yarn add typetags

Check the reference here

Usage ⚡️

The TypeTags object contains a list of strings, each representing an object type. You can use it to check if an object's typetag matches the default tag of its data type.

import { TypeTags } from 'typetags'

const o = { foo: 'bar' }

if (o.toString() !== TypeTags.Object) {
  doSomething()
}

The getTag function can be used to retrieve an object's typetag. Behind the curtains, all it does is to call Object.prototype.toString over any value and return the result.

const { getTag } = require('typetags')

const o = { foo: 'bar' }

const tag = getTag(o)

console.log(tag) // → '[object Object]'

There are two kinds of predicate functions to help us with assertions: generics and specifics.

Generics

Used for overall checks. For example, to check if an object has a default typetag:

const { isDefaultTag } = require('typetags')

const o = Object.create(null)

isDefaultTag(o) // → false

Specifics

Allow us to check for specific tags:

const { isArrayTag, getTag } = require('typetags')

const arr = [1, 2, 3]
const tag = arr.toString() // → 1,2,3

isArrayTag(tag) // → false

// however
console.log(getTag(arr)) // → '[object Array]'

Check this page for a reference list of all predicates

Bundles

esm

import { isDefaultTag } from 'typetags'

cjs

const { isDefaultTag } = require('typetags')

umd

<script src="dist/umd/typetags.min.js"></script>

Using typetags to detect object class

Every object has a toString() method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected.

By default, the toString() method is inherited by every object descended from Object. If this method is not overridden in a custom object, toString() returns "[object type]", where type is the object type. The following code illustrates this:

const o = new Object()
o.toString() // → [object Object]

See Mozilla MDN Web Docs

Although using toString() in this way is unreliable, as objects can change the behavior of Object.prototype.toString() this library might be helpful when you need to compare objects' tags inside a procedure call or if you just need a quick reference.

const { TypeTags, getTag } = require('typetags')

function isArray (value) {
  return typeof value === 'object' && getTag(value) === TypeTags.Array
}